这个问题已经被问到,建议的解决方案是使用“绑定(bind)”。但是如何在这种情况下使用“绑定(bind)”?
var Fun = function(){
this.count = 100;
}
Fun.prototype.f = function(){
console.log("in f : " + this.count);
}
Fun.prototype.g = {
f : function(){
console.log("in g-f : " + this.count);
// Is it possible to use 'bind' here to access 'this' of 'Fun'
}
}
fun = new Fun();
fun.f(); // Results - in f : 100
fun.g.f(); // Results - in g-f : undefined
fun.g.f.bind(fun)(); // Results - in f : 100
是否可以在 g.f
中使用 bind
使得 fun.g.f()
将在 f 中给出结果 :100
?
最佳答案
Is it possible to use 'bind' here to access 'this' of 'Fun'
不,因为在您创建第二个 f
时没有要绑定(bind)的 this
。您必须改为在 Fun
中执行此操作:
var Fun = function(){
this.count = 100;
this.g = {
f: function() {
console.log("in g-f : " + this.count);
}.bind(this)
};
};
或者没有绑定(bind):
var Fun = function(){
var t = this;
this.count = 100;
this.g = {
f: function() {
console.log("in g-f : " + t.count);
}
};
};
这确实涉及为每个实例创建一个新函数。现代浏览器引擎将在实例之间重用函数的代码,即使创建了不同的函数对象。
如果您想从原型(prototype)中使用 f
的主体,这也是可能的:如您所示,将 g
放在原型(prototype)上,然后:
var Fun = function(){
var t = this;
var oldg = this.g;
this.count = 100;
this.g = {
f: function() {
return oldg.f.apply(t, arguments);
}
};
};
现在,如果 Fun.prototype.g.f
在创建实例后发生变化,您将使用更新后的版本。但是,如果 Fun.prototype.g
被替换为对新对象的引用,它就会崩溃。
关于javascript - 在原型(prototype)中保留 'this' 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32626114/