【发布时间】:2014-03-12 21:34:52
【问题描述】:
在下面的代码中,我想知道上下文是如何绑定到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?
谢谢
【问题讨论】:
-
除了绑定之外,你还可以使用闭包,它们是 JavaScript 中非常强大的工具:在stackoverflow.com/a/16063711/1641941“this 变量”下
标签: javascript this bind melonjs