绑定与未绑定函数

Bho*_*yar 1 javascript

什么是绑定函数和未绑定函数?

nee*_*lsg 5

我创建了一个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)

  • 没问题。我以为有人至少应该给你一个体面的答案 (2认同)