谁能向我解释为什么“b”返回未定义以及如何解决这个问题?当我通过引用调用原型函数时,为什么“this”范围会丢失?
MyClass = function(test) {
this.test = test;
}
MyClass.prototype.myfunc = function() {
return this.test;
}
var a = new MyClass('asd').myfunc();
var b = new MyClass('asd').myfunc;
// Returns "asd" correctly
console.log(a)
// Returns undefined??
console.log(b())
=== 编辑/解决方案 ===
正如 plalx 所写,在我的例子中,正确的解决方案是使用 .bind()。所以结果看起来像这样:
MyClass = function(test) {
this.test = test;
}
MyClass.prototype.myfunc = function() {
return this.test;
}
var a = new MyClass('asd').myfunc();
var b = new MyClass('asd'),
bfunc = b.myfunc.bind(b)
// Returns "asd" correctly
console.log(a)
// Also returns "asd" correctly!
console.log(bfunc())
如果您想要这种行为,您需要显式绑定 this 值。
var c = new MyClass('asd'),
b = c.myfunc.bind(c);
console.log(b());
默认情况下,this
将指向leftSide.ofTheDot();
在调用中,或者简单地调用该函数的对象.
注:打电话b();
是相同的window.b();
.
将每个函数绑定到对象实例是可能的,但效率相当低,因为函数将不再在实例之间共享。
E.g.
function MyClass(someVal) {
var me = this;
me.someVal = someVal;
me.someFn = function () {
return me.someVal;
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)