[英]Passing method name as a callback VS. wrapping it with annoymous function
我有一個#test按鈕。
var obj = {
name: "John",
test: function() {
console.log('name '+ this.name );
}
};
$("#test").on( "click", obj.test);
這將記錄一個空字符串(記錄typeof this.name給出一個字符串)。
編輯:我知道此上下文成為按鈕,因此this.name不返回任何內容。
與
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。
關於解決this
。 如果您使用$("#test").on("click", obj.test);
那么this
將是按鈕,但如果你通過一個封閉那么this
將是obj
。
當我打電話obj.test那么this
測試將OBJ。
jQuery將設置this
是當它被點擊,從而通過obj.test沒有提及OBJ是按鈕this
會破壞你的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.