在下面的代码中,我想知道上下文是如何绑定(bind)到 this
的:
在 obj.myMethod();
中,上下文被赋予对象。所以记录它会给出对象。
在 var myFun = obj.myMethod;
和 myFun();
中,上下文被赋予窗口。
唯一的区别是您将函数设置为一个变量。
var obj = {
myMethod : function () {
console.log(this); //'this' is bound to context of object
}
};
obj.myMethod(); //calling object property directly = Object {myMethod: function}
var myFun = obj.myMethod;
myFun(); //but setting obj method property to a variable and running gives Window as context
编辑:
正在关注 this melonJS tutorial ,我很困惑这个回调是如何使用的(向下滚动到第 2 部分:加载我们的关卡,您将看到完整的代码)
// Set a callback to run when loading is complete.
me.loader.onload = this.loaded.bind(this);
我读了this tutorial on callbacks ,所以我明白它们的用途……但我不明白。它说 this.loaded.bind(this)
第一个和第二个 this
语句有什么区别?他们不一样吗?为什么我需要调用 this
然后调用 .loaded.bind()
然后再次传入 this
?
因此,在您的示例中,您说我可以通过执行 var bindMe = obj.myMethod.bind(obj);
来保持上下文,在这种情况下,您使用的是 this
因为你已经在对象 game
中了?那么 this
是指所有者 game
吗?
谢谢
最佳答案
简答
在表达式中
obj.f()
f
中的 this
将绑定(bind)到 obj
的值( 左侧的表达式)。
)。
如果一个函数被“单独”调用,即
f()
然后 f
中的 this
绑定(bind)到全局对象(在浏览器中,window)。
也就是说,您可以使用 .bind
函数预先设置上下文,即
var g = obj.f.bind(obj);
f(); // success! this == obj
比较https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
您可能还想看看 .call
和 .apply
函数。
要点:函数不携带上下文。 obj.f
是成员访问,它所做的只是从obj
返回属性f
的值。当您调用函数时设置上下文,obj.f()
或 f()
in f
存在于全局范围内,在这种情况下,上下文将是全局对象。
长答案
阅读规范! :) http://www.ecma-international.org/ecma-262/5.1/#sec-10.3
关于javascript - 对原型(prototype)绑定(bind)感到困惑,这个声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22364352/