我创建了一个JSFiddle以说明我对差异的理解。未绑定函数是未绑定到对象的this函数,因此该函数引用全局(窗口)对象。您可以通过使函数成为对象的方法来绑定函数,也可以使用该.bind()方法显式地对其进行绑定。我在代码中演示了不同的情况:
// 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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2187 次 |
| 最近记录: |