2011-09-30 74 views
4

我试图定义一个类,在它的构造函数,实例化其他对象,并将它们传递对自身的引用:参考当前对象的构造

var Child = function(m) { 
    var mother = m; 

    return { 
    mother: mother 
    } 
} 

var Mother = function() { 
    var children = makeChildren(); 

    return { 
    children: children 
    } 

    function makeChildren() { 
    var children = []; 
    for (var i = 0; i < 10; i++) { 
     var c = new Child(this);  // <--- 'this' is an empty object here 
     children.push(c) 
    } 
    return children; 
    } 
} 

这不起作用,和儿童实例最终会在其mother属性中有一个空对象。什么是正确的方法来做到这一点?

回答

3

Javascript的this不是词汇。这意味着makeChildren得到它的自己this而不是得到Motherthis你想要的。

为此设置一个普通变量并代之以使用它。

var that = this; 
function makeChildren(){ 
    blabla = that; 
} 

我不认为这样做是刚够虽然。通过从构造函数中返回一个对象,您将忽略this。设置的东西:

this.children = children; 

而不是返回一个新的对象。

+0

设置'this.children = makeChildren()'工作。这通常被认为是比从构造函数返回对象更好的模式吗? – Andre

+0

它只是当做一个使用'new'语法的构造函数时,你得到一个'this'来处理(并且这个继承自原型等)。如果你打算有一个函数返回它自己的东西,不需要访问这个继承或访问原型方法,你可能会使它成为一个普通的非构造函数。 (并且将名称改为非大写字母,Convention认为对于需要'new'操作符的东西) – hugomg

1

你可以尝试传递一个参考妈妈的对象,当你从母亲对象中调用makeChildren(),像这样也许:

var Mother = function() { 
    var children = makeChildren(this); 
} 

的makeChildren()函数就可以接受作为参数参考,你可以使用:

function makeChildren(ref) 
var c = new Child(ref); 

不知道这是否会工作,但它可能是值得一试。

+1

用魔法'这个'变量玩游戏通常会让一个人失踪。我喜欢这个解决方案,因为它很简单,直接,而且'makeChildren'不必以特殊的方式被调用以使其正常工作。 –

1

嵌套函数不继承其父this,所以内makeChildren()this是不一样的母亲构造内的this除非你明确地把它叫makeChildren()时:

var children = makeChildren.call(this); 

这应该工作而不需要对代码进行任何更改。查看more detail about .call()的MDN。

另外,您可以参考保存到this并传递到函数:

var Mother = function() { 
    var self = this; // <-- new variable 

    var children = makeChildren(); 

    return { 
    children: children 
    } 

    function makeChildren() { 
    var children = []; 
    for (var i = 0; i < 10; i++) { 
     var c = new Child(self);  // <--- change 'this' to 'self' 
     children.push(c) 
    } 
    return children; 
    } 
} 

一个函数中的局部变量是嵌套函数访问。

+0

自变量只能从Mother函数内访问吗?除非你明确地通过参考? –

+0

@jayp:内部函数可以使用其范围内的所有变量,这包括来自外部函数的变量。 – hugomg

+0

出于某种原因,我认为makeChildren不是一个内在的功能,但分开 - 显然我没有正确阅读。谢谢。 –

0
var Child = function(m) { 
    var mother = m; 

    return { 
     mother: mother 
    } 
}; 

var Mother = function() { 
    if (!(this instanceof Mother)) { 
     return new Mother(); 
    } 

    var that = this; 

    var makeChildren = function() { 

     var children = []; 
     for (var i = 0; i < 10; i++) { 
      var c = new Child(that); // <--- 'that' is the reference to Mother 
      children.push(c) 
     } 

     return children; 
    }; 

    var children = makeChildren(); 

    return { 
     children: children 
    } 
}; 

然后执行:

var m = Mother(); 

前三行的Mother对象确保that值是Mother实例,而不是全局对象。没有它们,你总是必须写:

var m = new Mother();