2013-10-13 35 views
1
.bind()時

只是想出來一個概念證明與.bind(),發現如果我嘗試在此代碼使用.bind(),我得到一個意外的標記「」:意外標記「。」在JavaScript中使用

var myObj = { 
    foo: function(){ 
     function bar(){ 
      console.log(this); 
     }.bind(this); // errors 
     bar(); 
    } 
} 

myObj.foo(); 

然而,如果我這樣做:

var myObj = { 
    foo: function(){ 
     var bar = function(){ 
      console.log(this); 
     }.bind(this); 
     bar(); 
    } 
} 

myObj.foo(); 

這很好。沒有錯誤。有人可以解釋這種行爲嗎?我猜這是在解析函數時做的,但如果有人有更深入的解釋,那會很棒!

+2

第一個版本是一個函數聲明,而第二個是一個函數_value_的分配。 – thebjorn

回答

3

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)(); 
    } 
} 
+0

也很好注意,這不是一個函數表達式聲明具有「較高優先級」 - 讓它一個,你應該將它賦值給一個變量或使用括號。 –

+0

謝謝,我想我有更多的工作原因,而不是爲什麼它不工作。我想我需要更多地瞭解底層函數聲明中發生了什麼。 – benhowdle89

+0

@ benhowdle89 - 當然,很高興我幫了忙。如果你想更詳細地理解函數,綁定,範圍等,除了[Dmitry Soshinkov的博客系列](http://dmitrysoshnikov.com/ecmascript/),我無法推薦任何東西 - 讀它兩次左右你會得到這一切:) – kamituel