tc39 / proposal-bind-operator

This-Binding Syntax for ECMAScript
1.75k stars 30 forks source link

class method binding #16

Closed idoros closed 8 years ago

idoros commented 9 years ago

it would be nice to have the same ability in classes, which would give automatic binding to class instance for selected methods:

class Foo{
 method(){}
 ::boundToInstanceMethod(){ 
  // this is always referenced to the instance  
 }
}
zenparsing commented 9 years ago

Thanks @idoros . Developers commonly want methods of a class autobound. Unfortunately, this proposal doesn't offer the appropriate semantics to support this, since at class definition time there's no instance to bind the method to.

Is there a particular use case that the unary bind operator doesn't address?

class Foo {
    method() {}
}

let f = new Foo();
let boundMethod = ::f.method;
nathggns commented 9 years ago

Could you not do a syntactical transform like the following?

class Foo {
    ::someMethod() {
        // this will always be instance of Foo
    }
}
var Foo = (function() {
    var Foo = function() {
        this.someMethod = this.someMethod.bind(this);
    };

    Foo.prototype.someMethod = function() {
        // this will always be instance of Foo
    };

    return Foo;
})();
idoros commented 9 years ago

@nathggns, +1 That was what I was thinking...

zenparsing commented 8 years ago

Perhaps this could be added in the future, but closing for now.