-2
什麼是綁定函數和未綁定函數?綁定vs未綁定函數
什麼是綁定函數和未綁定函數?綁定vs未綁定函數
我創建了一個JSFiddle來說明我的不同的理解。未綁定函數是一個未綁定到對象的函數,因此該函數中的this
引用了全局(窗口)對象。您可以通過將其作爲對象的方法來綁定某個函數,也可以使用方法明確地綁定該函數。我演示了我的代碼中的不同情況:
// A function not bound to anything. "this" is the Window (root) object
var unboundFn = function() {
alert('unboundFn: ' + this);
};
unboundFn();
// A function that is part of an object. "this" is the object
var partOfObj = function() {
alert('partOfObj: ' + this.someProp);
};
var theObj = {
"someProp": 'Some property',
"theFn": partOfObj
};
theObj.theFn();
// A function that is bound using .bind(), "this" is the first parameter
var boundFn = function() {
alert('boundFn: ' + this.someProp);
};
var boundFn = boundFn.bind(theObj);
boundFn();
非常感謝。 –
沒問題。我認爲有人應該至少嘗試給你一個體面的答案 – neelsg