Concise Method Binding

Brendan Eich brendan.eich at gmail.com
Wed Nov 11 18:56:20 UTC 2015


Your Person::greet example is canonically used to demonstrate dynamic
|this|. How does it motivate the instance-bound method in class use-case?
Perhaps show some example that justifies the method-per-instance overhead.

/be

On Wed, Nov 11, 2015 at 10:25 AM Bergi <a.d.bergi at web.de> wrote:

> 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
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20151111/3572a706/attachment.html>


More information about the es-discuss mailing list