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
I would do this:
function Game() {
this.id;
this.stats = new Stats(this);
}
function Stats(game) {
this.property;
this.method = method;
function method() {
this.property;
game.id;
}
}
var game = new Game;
game.stats.method();
The reasons are as follows:
Yes, that's exactly the way to go.
Notice that the this
keyword in your method()
will hold the nested_object
, not your Game
instance. You can get a reference to that only by using a variable pointing to:
function Game() {
var that = this; // the Game instance
this.id = …;
this.nested_object = {
property: "nested!",
method: function() {
this.property; // nested! (=== that.nested_object.property)
that.id // the game property
}
};
}
var game = new Game;
game.nested_object.method();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With