Javascript 将方法名作为回调传递,而不是用函数包装
我有一个按钮测试 这将记录一个空字符串(记录类型This.name给出一个字符串) 编辑:我知道此上下文将成为按钮,因此this.name不返回任何内容 对Javascript 将方法名作为回调传递,而不是用函数包装,javascript,callback,Javascript,Callback,我有一个按钮测试 这将记录一个空字符串(记录类型This.name给出一个字符串) 编辑:我知道此上下文将成为按钮,因此this.name不返回任何内容 对 var obj = { name: "John", test: function() { console.log('name '+ this.name ); } }; $("#test").on( "click", function() { obj.test(); //logs John }); 有什么区别 编
var obj = {
name: "John",
test: function() {
console.log('name '+ this.name );
}
};
$("#test").on( "click", function() {
obj.test(); //logs John
});
有什么区别
编辑:如何用annon函数包装obj.test(),使其行为与上面的不同?真正的区别在于对象测试所操作的对象。在第二个示例中调用函数时,您正在使用obj上下文调用函数。在第一个示例中,您传递的是对函数的引用,而不是它所附加到的上下文。在第一种情况下,当调用函数时,它实际上是在操作全局范围 要测试这一点,请尝试推出:
var name=“eiriki”;在全局范围内的某个地方,然后运行您的函数。它可能会打印出eiriki,除非您已经为它指定了其他内容 这是关于解决
这个问题的。如果您在(“单击”,对象测试)上使用“#test”)
然后此
将是按钮,但如果您传递一个则此
将是obj
当我调用obj.test时,test中的这个
将是obj
JQuery将在单击时将this
设置为按钮,以便通过obj.test而不引用obj此
将中断obj.test功能
解决此问题的最佳方法是使用(IE<9时需要):
我认为这不是真的。第一个示例中的上下文是button对象。@如果eirikrl是正确的,jQuery将把
这个设置为按钮。当您传递一个闭包时,闭包中的此
仍将是按钮,但因为您将调用obj.test()
则此
将是测试函数中的obj。更多细节请参见我的答案。这不是一个“闭包”问题。标签被移除了,我想是的。第二个例子使用了一个闭包,使得它的行为与第一个例子不同。不,这是关于这个
的解析。在这两个例子中都没有闭包。
var obj = {
name: "John",
test: function() {
console.log('name '+ this.name );
}
};
$("#test").on( "click", function() {
obj.test(); //logs John
});
var obj = {
name: "John",
test: function () {
console.log('This is:' + this.toString());
},
toString: function () {
return "It's test"
}
};
$("#test").on("click", function () {
// by the way; this here is the button
console.log("what's this here:", this.toString());
obj.test(); //works but creates a closure
});
$("#test").on("click", obj.test);//breaks, this will be button in test
$("#test").on("click", obj.test.bind(obj));//works
// now to show how this is resolved
window.mytest = obj.test;
window.mytest();// this is window
var obj2 = {
toString: function () {
return "this is obj2";
}
};
obj2.test = obj.test;
obj2.test();//this is obj2