3 ms·
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.
by supergreg 9y 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);`
- spraak 9y agoThat'd be awesome. Submit a proposal! https://github.com/tc39/proposals https://github.com/tc39/proposals
- supergreg 9y agoLooked 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 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/ https://babeljs.io/docs/plugins/transform-class-properties/
- martin-adams 9y agoInteresting, 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?
- abiox 9y ago> that would mean you would have confusion does this confusion not exist now?
- martin-adams 9y agoDon’t know, my concern was what the intended behaviour was if a declaration stated the bind context as well as the caller.
- always_good 9y agoAlready exists. class Foo { bar = () => { console.log(this); } } Has to be compiled with Babel, though.
- bramen 9y agoThere'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 https://github.com/tc39/proposal-class-fields.