0

In ES5 one would create a bound method like so:

function FakeClass() {
    this.foo = this._foo.bind(this);
    // or, with Underscore/Lodash
    // this.foo = _.bind(this.foo, this);
    // or
    // _.bindAll(this, 'foo');
}
FakeClass.prototype._foo = function() { ...

With ES6 syntax this doesn't seem to go away; it seems like I still have to explcitily bind the method:

class FakeClass {
    constructor() {
        this.foo = this._foo.bind(this);
    }
    _foo() { ...
}

So, my question is: there a better way that's actually part of (current or planned) JS?

NOTE: I've seen some Stack Overflow answers mention this syntax:

class FakeClass {
    foo = () => { ...
}

However when I try that syntax only Babel allows it; Chrome and my IDE both tell me that's invalid syntax. Presumably this is because the foo = () => { syntax comes from some unfinished ES7 or ES8 proposal. However, I haven't been able to Google an answer, and until I do I'm hesitant to add (potentially invalid in the future) syntax to my code.

machineghost
  • 33,529
  • 30
  • 159
  • 234
  • While it's not exactly the same title question, I think the duplicate answers all your questions. – Bergi Feb 19 '16 at 02:38
  • It confirms that the `=>` syntax is not something I want to use, and that (unfortunately) I'm stuck with the `this.foo = this._foo.bind(this)` pattern. Thanks. – machineghost Feb 19 '16 at 18:41

0 Answers0