bind()
是Function.prototype
的方法。因此它應該在函數對象上調用,並返回一個具有相同主體但與this
綁定的值不同的新函數。
當使用函數聲明(你的第一個場景),你沒有得到的回報函數對象(您的第一個場景),從而錯誤。沒有什麼可以撥打bind()
。
第二個作品,因爲你分配給變量的函數,所以你得到一個函數對象。
考慮:
function a() {
return this.variable;
}
a(); // === undefined, because "this" is bound to the global object,
// and global object does not have "variable" defined.
// When not in strict mode, global object === window (in browser env).
var b = window.a.bind({variable: 'value'});
// Since a() was declared, it is a property of the global object (window).
// Lets get it and bind to some object.
b(); // === 'value' - because 'b' is essentialy 'a' bound to {variable: 'value'}.
window.variable = 'other value'; // assign variable to global object
a(); // === 'other value'
b(); // === 'value' - it is not bound to global object, so no change here.
因此,在您例如,你可以這樣做:
var myObj = {
foo: function(){
function bar(){
console.log('this', this);
}
var bar2 = bar.bind(this);
bar2();
// Or:
// bar.bind(this)();
}
}
第一個版本是一個函數聲明,而第二個是一個函數_value_的分配。 – thebjorn