Concise Method Binding
Bergi
a.d.bergi at web.de
Wed Nov 11 18:24:29 UTC 2015
Gilbert B Garza schrieb:
> Forgive me if I'm missing the point, but isn't the entire purpose of using
> classes to make all instances share the same function in memory via `this`
> ? If you want methods to always be bound, why not use closures instead?
>
> ```js
> function Person (name) {
> var person = this
> person.greet = function () {
> return person.name + " says hi!";
> };
> }
Yes, the point of prototypes is sharing. But maybe we don't want (cannot
use) that.
The point of the `class` syntax is just to enable a more declarative
definition of class methods - which should include some way to create
instance methods as well, simply because they're needed often enough.
And being able to declare methods that will get bound outside of the
constructor (even if that's a bit confusing) avoids much boilerplate
again. Just compare
```js
class Person extends … {
constructor(name) {
super(name);
this.greet = () => {
return this.name + " says hi!";
};
}
}
```
vs
```js
class Person extends … { // with default constructor
::greet() {
return this.name + " says hi!";
}
}
```
Regards,
Bergi
More information about the es-discuss
mailing list