我正在阅读一个教程,所以我可以理解_.bind和_bindAll:http://blog.bigbinary.com/2011/08/18/understanding-bind-and-bindall-in-backbone.html
该网站具有以下代码
function Developer(skill) {
this.skill = skill;
this.says = function(){
alert(this.skill + ' rocks!');
}
}
var john = new Developer('Ruby');
john.says(); //Ruby rocks!vs
function Developer(skill) {
this.skill = skill;
this.says = function(){
alert(this.skill + ' rocks!');
}
}
var john = new Developer('Ruby');
var func = john.says;
func();// undefined rocks!为什么存储对函数的引用,然后调用该函数会导致该函数的上下文为window?
发布于 2013-02-15 00:09:46
当你执行
a.b();那么a就是b (b中的this)的执行上下文,除非b是一个绑定函数。
如果你没有a,那就是如果你有
b();然后它就像是
window.b();因此,window是执行b的上下文。
还要注意的是
a.b();等同于
b.call(a);和
b();等同于
b.call(); // call replaces its first argument by the global object if it's null or undefined如果你想绑定上下文,你可以这样做(在现代浏览器上)
var func = john.says.bind(john);
func();或者(更经典的)使用闭包:
var func = function(){john.says()};
func();发布于 2013-02-15 00:17:14
因为"this“关键字在调用时绑定,而不是在定义时绑定。
当你调用john.says()时,它就像是在做john.says.apply(john)。
当你调用func()时,它就像是在做func.apply()。
耶胡达·卡茨对"JavaScript function invocation and this“有一个很好的解释。
https://stackoverflow.com/questions/14879037
复制相似问题