I have a question about JavaScript. I’m currently using code similar to the code below:
function Game() {
}
I want to nest objects, so I can access them like so:
var a = new Game();
a.nested_object.method();
a.nested_object.property;
How would I go about doing this? Would I use a function or {}? Or does it even matter? The code below is an example code of what I am referring to.
function Game() {
this.id;
var stats = {};
}
Like I’ve stated above, can I access stats like so:
var a = new Game();
a.stats
Yes, that’s exactly the way to go.
Notice that the
thiskeyword in yourmethod()will hold thenested_object, not yourGameinstance. You can get a reference to that only by using a variable pointing to:Because of that nested objects on the prototype (where you don’t have a variable containing the instance) will seldom make much sense – see Crockford's Prototypal inheritance – Issues with nested objects.