views:

7013

answers:

3

Previously, when I needed to store a number of related variables, I'd create a class.

function Item(id, speaker, country) {
    this.id = id;
    this.speaker = spkr;
    this.country = country;
}
var myItems = [
    new Item(1, 'john', 'au'),
    new Item(2, 'mary', 'us')
];

But I'm wondering if this is a good practice. Are there any other, better ways to simulate a struct in Javascript?

+4  A: 

I always use object literals

{id: 1, speaker:"john", country: "au"}
vava
wouldn't that make it much harder to maintain (should you want to add a new field in the future), and also much more code (retyping "id", "speaker", "country" every time)?
nickf
It is exactly as maintainable as solution with classes because JavaScript doesn't care about number of arguments you call the function with. Retyping is not an issue if you using right tools like Emacs. And you can see what equals what which makes mistakes like swapping arguments obsolete.
vava
But the biggest pro is that you would write less code and it'll be cleaner :)
vava
+1  A: 

I use objects JSON style for dumb structs (no member functions).

Robert Gould
+8  A: 

The only difference between object literals and constructed objects are the properties inherited from the prototype.

var o = {
  'a': 3, 'b': 4,
  'doStuff': function() {
    alert(this.a + this.b);
  }
};
o.doStuff(); // displays: 7


You could make a struct factory.

function makeStruct(names) {
  var names = names.split(' ');
  var count = names.length;
  function constructor() {
    for (var i = 0; i < count; i++) {
      this[names[i]] = arguments[i];
    }
  }
  return constructor;
}

var Item = makeStruct("id speaker country");
var row = new Item(1, 'john', 'au');
alert(row.speaker); // displays: john
MizardX