Typescript: Add the ability to bind methods

Created on 25 Jun 2017  路  7Comments  路  Source: microsoft/TypeScript

Add the ability autobind, and it is already tired to write -

.ts -

class SomeClass {
  public bind someMethod(): void {}
}

.js -

class SomeClass {
  constructor(){
    this.someMethod = this._someMethod.bind(this);
  }
  _someMethod(){}
}
Out of Scope Suggestion

Most helpful comment

You probably had not thought of that in this._method.bind(this) logic is not duplicated!

This is not how it works.

I shouldn't have to say this, but after five years of getting bug reports and suggestions about this, we really have thought about how this might be solved.

All 7 comments

This looks like a job for decorators.

This is something that would need to be an addition to ECMAScript itself, or that could potentially be accomplished through decorators. Though you can easily get around this with

class SomeClass {
  someMethod = () => {
    // ...
  }
}

@DanielRosenwasser's suggestion of just using a lambda function property is so simple compared to using decorators that I feel silly for even suggesting them. If there is a benefit of decorators, it's that you would get to use an explicit @bind or @instanceBound annotation if you think the () => {} syntax is too cryptic. But a comment would probably address that.

@DanielRosenwasser
The lambda as a class field - wrong!

class SomeClass {
    public handler(): void { } // set in prototype
}
new SomeClass();
new SomeClass();
new SomeClass(); // only one method handler prototype!

class SomeClass {
    public handler = (): void => { } // set in this
}
new SomeClass();
new SomeClass();
new SomeClass(); // 3 function handler!

@jcalz
The decorator is too slow for games!

@acopalipsis Daniels's suggestion is equivalent to the JS you wanted.

Either you get 1 bound closure per method per instance, or 1 unbound closure per method per class. There's no solution that gives you 1 bound closure per method per class.

@RyanCavanaugh You probably had not thought of that in this._method.bind(this) logic is not duplicated!
With lambda expression logic will be duplicated! Open!

You probably had not thought of that in this._method.bind(this) logic is not duplicated!

This is not how it works.

I shouldn't have to say this, but after five years of getting bug reports and suggestions about this, we really have thought about how this might be solved.

Was this page helpful?
0 / 5 - 0 ratings