2014-07-15 72 views

回答

3

我创建了一个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(); 
+0

非常感谢。 –

+1

没问题。我认为有人应该至少尝试给你一个体面的答案 – neelsg