我在下面的情况中感到困惑:
function foo() {
}
foo.prototype.bar1 = function() {
console.log(this); // shows "Window"!!
}
foo.prototype.bar2 = function(func) {
func();
}
var f = new foo();
f.bar2(f.bar1);
为什么console.log(this)的结果会是“Window”?我认为无论您如何调用类的公共函数,"this"应该始终指向 "foo"。
还有,避免这种错误的正确方法是什么?
谢谢
func.apply(this)
来获得预期的行为,我认为。 - Waleed Khanfunc.call(this)
应该可以。 - elclanrsbar2
时的 ThisBinding 是“预期的”。 - user2246674