2017-09-11 2 views
1

Ich habe eine ES6-Klasse, die eine Methode mit async.waterfall enthält. Waterfall erhält als erstes Argument ein Array von Funktionen. So mache ich es so:"This" in Funktionen, die zu einem Array gehören

class RequestLog { 
    mainMethod() { 
     async.waterfall([ 
      this.method1, 
      this.method2, 
      this.method3 
     ]); 
    } 

    method1(cb) { 
     console.log(this); // outputs null 
     cb(); 
    } 
} 

Aber wie oben erwähnt, in der ersten Funktion I Kirchenschiff this === null. Wenn es anon Funktion wäre, würde ich schreiben:

aber ich möchte getrennte Methoden für Code Klarheit haben. Also, wie übergebe ich this an benannte Funktion in einer Klasse?

Antwort

3

Sie müssen die Methoden an this binden. Hier sind einige Möglichkeiten:

Option 1 - sie binden, wenn Sie sie verwenden:

mainMethod() { 
    async.waterfall([ 
     this.method1.bind(this), 
     this.method2.bind(this), 
     this.method3.bind(this) 
    ]); 
} 

Option 2 - binden sie im Konstruktor:

class RequestLog { 
    constructor() { 
    this.method1 = this.method1.bind(this); 
    this.method2 = this.method2.bind(this); 
    this.method2 = this.method3.bind(this); 
    } 
    ... 
} 

Option 3 - Binden Sie sie unter Verwendung von proposal-class-fields, die babels Class properties transform oder Stage 2 preset erfordert:

class RequestLog { 
    method1 = (cb) => { 
     console.log(this); // outputs null 
     cb(); 
    } 
} 

Option 4 - verwenden proposal-bind-operator, die Function bind transform Babels erfordert:

mainMethod() { 
    async.waterfall([ 
     ::this.method1, 
     ::this.method2, 
     ::this.method3 
    ]); 
} 

Option 5 - sie von einem Pfeil-Funktion aufrufen:

mainMethod() { 
    async.waterfall([ 
     (cb) => this.method1(cb), 
     (cb) => this.method2(cb), 
     (cb) => this.method3(cb) 
    ]); 
} 
+0

Sehr umfassende Antwort, die beide prägnant und umfassend. Ich wählte die fünfte Option, da sie 'bind' nicht verwendet (ich hoffte, dass ich sie dank ES6 nie wieder brauche) und zeigt an, welche Parameter zu jeder Funktion gehören. Danke vielmals! – Forseti

Verwandte Themen