2017-06-13 2 views
-1

Wie kann ich bind() in dem folgenden Code, so dass ich den Umfang von „dieser“Mit bind in Javascript

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' - Wo ist' indexScore'? Welchen Wert von 'this' willst du binden? – Quentin

Antwort

0

wie diese Versuchen nicht verlieren lassen Sie mich wissen, wenn ich falsch bin hier

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

Sie können call() oder apply() wie folgt verwenden:

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); 
}); 

oder mit 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 ]); 
}); 

Beide Methoden binden das erste Argument als this Wert. Der Unterschied ist, dass apply() ein Array von Funktionsargumenten als zweiten Parameter hat, während call() nur ein Argument mehr als der anfängliche Funktionsaufruf hat (der erste ist der this Wert der Funktionen). Weitere Informationen finden Sie unter answer.

+0

[gelöschter Kommentar - ich habe nicht aufgepasst] – shabs

0

Die einfache Antwort ist die anonyme Funktion in Klammern zu wickeln und rufen bind(this) darauf:

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

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

}).bind(this)); 

Die nuancierter Antwort ist, dass Pfeil Funktionen nicht binden ihre eigenen this - sie sind „lexikalische "- das sollte eigentlich nicht nötig sein.