中的对象构造函数

中的对象构造函数

本文介绍了定义一个“嵌套"JavaScript 中的对象构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在另一个对象中定义一个对象?我在想这样的事情:

Is it possible to define an object within another object? I'm thinking something like this:

function MyObj(name) {
    this.name = name;

    function EmbeddedObj(id) {
        this.id = id;
    }
}

然后我可以像这样创建一个 EmbeddedObj:

And I could then create an EmbeddedObj like this:

var myEmbeddedObj = new MyObj.EmbeddedObj();

奖励积分的模因:Objectception!:o

Meme for bonus points: Objectception! :o

推荐答案

是,也不是.

function MyObj(name) {
    this.name = name;
}
MyObj.EmbeddedObj = function EmbeddedObj(id) {
    this.id = id;
}
new MyObj.EmbeddedObj(42);

会运行,但它可能不会产生嵌入对象"的预期结果(见评论).

Would run, but it might not yield the expected results for "embedded object" (see comment).

请注意,在 new expr 的情况下,表达式是 first 求值的,因此,在这种情况下,它使用从 求值的函数对象创建一个新对象MyObject.EmbeddedObj 作为构造函数.(表达式中有一个带括号的愚蠢规则,但那是另一回事了.)

Note that in the case of new expr the expression is evaluated first so, in this case it creates a new object using the function-object evaluated from MyObject.EmbeddedObj as a constructor. (There is a silly rule with parenthesis in the expression, but that's another story.)

现在,如果需要父"和子"关系,可以使用更周到的方法来实现:

Now, if a "parent" and "child" relationship was desired, that could be done, using a more round-about method:

function Parent (name) {
   this.name = name;
   var parent = this; // for closure
   this.Child = function Child () {
      this.Parent = parent;
   }
}

// create new parent object
var parent = new Parent();
// each new parent has a different Child constructor and
// any function-object can be used as a constructor
var child = new parent.Child();
// true: child is "bound" to parent
child.Parent === parent;

这篇关于定义一个“嵌套"JavaScript 中的对象构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:09