2013-10-28 37 views
1

假设你有访问原型

function Thing() { 
    this.val = 1; 
} 

Thing.prototype.some = function() { 
    console.log('thing'); 
}; 

Thing.prototype.foo = { 
    bar: function() { 
    console.log(root.val); 
    } 
}; 

你如何能够得到this参考作为Thing例如,虽然还在坚持一个原型模型?

回答

4

使用该设置,唯一的方法是显式传递对象(“Thing”实例)作为参数,或使用.call().apply()

如果你实例化一个“东西”:

var thing = new Thing(); 

那么你可以到“栏”功能thing.foo.bar。从该参考援引:

thing.foo.bar(); 

this内部“BAR”的值将是在原型的“foo”的对象。然而,你可以使用.call()

thing.foo.bar.call(thing); 

然后在“酒吧”的调用this的确会实例化“物”的对象。

请务必记住,在JavaScript中,将对象属性设置为函数不会在对象和函数之间创建任何特殊关系。重要的是当指向表达式中的属性值时发现的关系。它始终是动态的,尽管遵循原型链的机制有点令人眩晕,但确定this的规则非常简单。

0

您可以将函数绑定到上下文而不执行它,就像call/apply一样。使用bind

例如:

function Thing() { 
    this.val = 1; 
} 

Thing.prototype.some = function() { 
    console.log('thing'); 
}; 

Thing.prototype.foo = { 
     bar: function() { 
     console.log(this.val); 
     } 
    } 

var thing = new Thing(); 
// bind instance's `foo.bar` to `thing` instance 
thing.foo.bar = thing.foo.bar.bind(thing); 
// now you can call it without providing `thing` as the context every time like wit apply/call 
console.log(thing.foo.bar()); 

它是事件可能结合foo.bar到东西的一个实例,但随后的事情的每一个实例已foo.bar绑定到的事情的共享实例。我不知道这是否是一个好主意,但它种工作方式:

function Thing() { 
    this.val = 1; 
} 

Thing.prototype.some = function() { 
    console.log('thing'); 
}; 

Thing.prototype.foo = { 
     bar: function() { 
     console.log(this.val); 
     }.bind(new Thing()) 
    } 

var thing = new Thing(); 

console.log(thing.foo.bar()); 
+0

我想真正让我想要的方式的必由之路,那么,会遍历这些方法和'bind'在构造函数中。这太糟糕了。谢谢 – bevacqua