1

I have a ES6 class that contains a method with async.waterfall. Waterfall gets an array of functions as its first argument. So I do it this way:

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

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

But as noted above, in first function I nave this === null. If it was anon function I'd write:

async.waterfall([ (cb) => { console.log(this) } ]);

but I want to have separated methods for code clarity. So, how do I pass this to named function inside a class?

Forseti
  • 2,587
  • 6
  • 21
  • 32

1 Answers1

3

You'll need to bind the methods to this. Here are some options:

Option 1 - bind them when you use them:

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

Option 2 - bind them in the constructor:

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

Option 3 - bind them using proposal-class-fields, which requires babel's Class properties transform or Stage 2 preset:

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

Option 4 - use proposal-bind-operator, which requires babel's Function bind transform:

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

Option 5 - call them from an arrow function:

mainMethod() {
    async.waterfall([
        (cb) => this.method1(cb),
        (cb) => this.method2(cb),
        (cb) => this.method3(cb)
    ]);
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Very comprehensive answer, both concise and comprehensive. I chose the fifth option as it doesn't use `bind` (I hoped I'll never need it again thanks to ES6) and shows what parameters go to each function. Thanks a lot! – Forseti Sep 11 '17 at 14:18