If you want to get the most bang for your buck, you can use a function, which allows you to set "public" and "private" variables. For example:
function Person (name, age) {
var number = (Math.random() * 100) | 0;
// number is private; there's no way to access it outside
// of the scope of this function
var surpriseParty = new Date(Date.now() + number*24*3600*1000);
// we're throwing you a party within the next 100 days
this.name = name; // public
this.age = age; // public
return {
getName: function () { return name },
getAge: function () { return name },
getPartyDate: function () { return surpriseParty }
}
}
As commented in the code above, now only certain variables can be accessed:
var p = new Person("royhowie", 18);
// p.getName() => "royhowie"
// p.name => "royhowie"
// p.getAge() => 18
// p.age => 18
// p.number => undefined
// p.surpriseParty => undefined
// p.getPartyDate() => date within the next 100 days
In truth, though, you should use whatever fits the bill best. The above method is an easy way to encapsulate data, but if you want everything to be public, use the normal object syntax:
var p = { name: "royhowie", age: 18, surpriseParty: new Date() };
I wouldn't recommend the self-executing anonymous function syntax. You should declare the function elsewhere (at least for debugging); this at least gives you the option of creating two different instances of that object.