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