简体   繁体   English

JavaScript嵌套对象

[英]JavaScript nesting objects

I have a question about JavaScript. 我有一个关于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: 原因如下:

  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. 模块化 - 您可以将游戏构造函数和stats构造函数放在两个不同的文件中。 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). 如果你使用对象文字表示法来创建它(如@Bergi所做的那样),那么stats对象可以访问游戏对象的私有成员(如果stats对象意外地改变了游戏对象的私有属性,这可能会适得其反。 )。
  4. Readability - Compare @Bergi's code and mine. 可读性 - 比较@ Bergi的代码和我的代码。 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. 您可以只看一眼代码并确切知道发生了什么。

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. 请注意, method()中的this关键字将包含nested_object ,而不是您的Game实例。 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 . 由于原型上的嵌套对象(你没有包含实例的变量)很少有意义 - 请参阅Crockford的Prototypal继承 - 嵌套对象的问题

将“嵌套”内容添加thisGame.prototype

[Edited to respond to comments below] [编辑回复以下评论]

How about this: 这个怎么样:

function Game() {

    this.nested_object = {
        method: function () {
            return 'method return value';
        },

        property: 'property value'
    };

};

var a = new Game();
alert( a.nested_object.method() );
alert( a.nested_object.property );

Just create the nested object in the constructor. 只需在构造函数中创建嵌套对象。

function Game() {
    this.stats = { lives: 3 };
};

var a = new Game();
-- a.stats.lives;

However, this can be annoying as in the implementation of Game you must refer to stats as this.stats . 但是,这可能很烦人,因为在Game的实现中你必须将stats称为this.stats The this 'es add up and confusion can arise when this refers to the wrong thing, for example inside a function(){} expression. this “ES加起来时可能出现的混淆this指的是错误的事情,例如一内部function(){}表达。

My preferred pattern looks like this. 我喜欢的模式看起来像这样。 It's essentially a classic OO getter function. 它本质上是一个经典的OO getter功能。

function Game() {
    var stats = { lives: 3 };
    this.stats = function() { return stats; };
};

var a = new Game();
-- a.stats().lives;

This should be more appropriate 这应该更合适

function Game() {
  this.id;
  this.stats = "Hello";
  return this;
}

var a = new Game();
alert(a.stats);

Basically in your case stats is a local variable , and the object created has no idea about the variable. 基本上在你的情况下, stats is a local variable ,创建的对象不知道变量。

Check Fiddle 检查小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM