Using structs in JavaScript (example, syntax)

Bearing in mind that I rarely use JavaScript and I’m not an expert in it, I like the idea of using something like a C-like “struct” in my JavaScript code, so I used the following approach on a recent project. First, I define my JavaScript struct:

function Book(title, href, imageUri, description) {
    this.title = title;
    this.href = href;
    this.imageUri = imageUri;
    this.description = description;
}

Then I define an array of Book types:

var popularBooks = [
    new Book(
        "Grokking Algorithms: An illustrated guide" ,
        "http://kbhr.co/grokking",
        "/images/books/grokking-algorithms-illustrated-guide-2.jpg",
        "Grokking Algorithms"
    ),
    new Book(
        "Scala for the Impatient (2nd Edition)" ,
        "http://kbhr.co/scala-imp",
        "/images/books/scala-for-impatient.jpg",
        "2nd Edition"
    ),
    // many more here ...
];

And then as just one example of how I use this, here’s a function I wrote that takes a Book as an input parameter and returns a string:

function htmlFromBook(book) {
    var html = '<div class="lhs-book" align="center"><a '
             + 'href="' + book.href + '" rel="nofollow"><img '
             + 'alt="' + book.title + '"'
             + 'title="' + book.title + '"'
             + 'src="' + book.imageUri + '"'
             + 'width="145" />'
             + '<br />' + book.description + '</a></div>';
    return html;
}

For many people the preferred approach to a problem like this might be to use JSON object literals, but I like the ideas of (a) having something that works as a constructor, and (b) being able to look at the Book function so I can see what a book template looks like. As I get older more of my code looks like a collection of data structures along with functions that operate on those structs, so while I may be in the minority here, I thought I’d share this “JavaScript struct” example, along with the JavaScript syntax needed to use this approach.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.