-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