Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript nesting objects

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
like image 923
JaPerk14 Avatar asked Feb 18 '23 21:02

JaPerk14


2 Answers

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:

  1. Separation of concerns - the game constructor can concentrate entirely on the game logic and the stats constructor will concentrate only on the statistics of the game.
  2. Modularity - You can put the game constructor and the stats constructor in two different files. This allows you to deal with them separately and makes the project easier to manage.
  3. Loose Coupling - The stats object doesn't need to know about the game object. So it's better to separate it from the game object. If you create it using an object literal notation instead (as @Bergi did) then the stats object has access to the private members of the game object (which could be counter-productive if the stats object accidently changes a private property of the game object).
  4. Readability - Compare @Bergi's code and mine. Separating the stats and the game object makes the code easier to read and understand. You can have one glance at the code and know exactly what's going on.
like image 122
Aadit M Shah Avatar answered Mar 04 '23 07:03

Aadit M Shah


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.

like image 43
Bergi Avatar answered Mar 04 '23 09:03

Bergi