Hacker News new | ask | show | jobs
by supergreg 3141 days ago
The case would be solved if they added some syntax to bind a function to the class. Something like

    class Foo {
      bind function bar() {
        console.log(this);
      }
    }
So behind the scene it would do `this.bar = this.bar.bind(this);`
4 comments

There's already a proposal for field declarations, where you can do the following:

  class Foo {
    bar = () => {
      console.log(this);
    }
  }
This basically puts `this.bar = () => console.log(this)` in the constructor, and since it's an arrow function it captures the correct context.

See https://github.com/tc39/proposal-class-fields.

That'd be awesome. Submit a proposal! https://github.com/tc39/proposals
Looked around and there's a proposal for an easier way to bind `this` and some discussion about extending that to class methods: https://github.com/tc39/proposal-bind-operator/issues/39

Using arrow functions at the class level would also solve this without adding new syntax. Edit, this is a thing already: https://babeljs.io/docs/plugins/transform-class-properties/

Interesting, that would mean you would have confusion if someone used your class like:

foo.bar.bind(somethingElse);

How would the callee know that this would potentially conflict?

> that would mean you would have confusion

does this confusion not exist now?

Don’t know, my concern was what the intended behaviour was if a declaration stated the bind context as well as the caller.
Already exists.

    class Foo {
      bar = () => {
        console.log(this);
      }
    }
Has to be compiled with Babel, though.