綁定

2017-06-13 35 views
-1

如何我可以使用綁定()在下面的代碼,這樣我不失去「這個」綁定

this.getContactName(id, (error, contactName) => { 
    if (error) return callback(error, null); 

    // want to access "this" here e.g., 
    // this.indexScore = 1 

    return callback(null, contactName); 
}); 
+0

'this.indexScore = 1' - where'indexScore'?你想綁定什麼'this'的值? – Quentin

回答

0

範圍嘗試這樣 讓我知道,如果我錯了這裏

this.getContactName(id, (error, contactName) => { 
    if (error) return callback(error, null); 

    // want to access "this" here e.g., 
    // this.indexScore = 1 

    return callback(null, contactName); 
}).bind(this); 
1

您可以使用call()apply()這樣的:

this.getContactName(id, (error, contactName) => { 
    if (error) return callback.call(this, error); 

    // want to access "this" here e.g., 
    // this.indexScore = 1 

    return callback.call(this, contactName); 
}); 

或用apply()

this.getContactName(id, (error, contactName) => { 
    if (error) return callback.apply(this, [ error ]); 

    // want to access "this" here e.g., 
    // this.indexScore = 1 

    return callback.apply(this, [ contactName ]); 
}); 

這兩種方法結合的第一個參數作爲this值。區別在於,apply()有一個函數參數數組作爲第二個參數,而call()只有一個參數比初始函數調用多(第一個是函數的this值)。有關更多信息,請參閱此answer

+0

[刪除評論 - 我沒有注意] – shabs

0

直截了當的答案是包裝的匿名函數在括號中並在其上調用bind(this)

this.getContactName(id, ((error, contactName) => { 

    if (error) return callback(error, null); 
    return callback(null, contactName); 

}).bind(this)); 

的更細緻的回答是箭頭的功能不綁定自己的this - 他們是「詞法範圍「 - 所以這實際上不是必須的。