是关于解决的this。如果您使用$("#test").on("click", obj.test);thenthis将是按钮,但如果您通过闭包则将this是obj.
当我调用 obj.testthis时,测试中将是 obj。
JQuery 将this在单击时设置为按钮,因此在不引用 obj 的情况下传递 obj.testthis会破坏您的 obj.test 函数。
解决此问题的最佳方法是使用Function.prototype.bind(您需要IE < 9的polyfil ):
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