Closed
Description
I noticed methods on all objects are unbound, e.g.
// https://tonicdev.com/marionebl/5755b0178b908f130020fd9d
var Github = require('github-api');
var github = new Github();
var getRepo = github.getRepo;
var repo = getRepo();
// => Cannot read property '_getFullName' of undefined
Of course this can be fixed easily by changing it to:
// https://tonicdev.com/marionebl/5755b4e28b908f130020fedb
var Github = require('github-api');
var github = new Github();
var getRepo = github.getRepo.bind(github);
var repo = getRepo();
This is rather clumsy and moves the work to bind the methods to their respective host objects to users although it could easily be done by the library.
- Are you interested in a PR that auto binds all methods?
- Which would be the preferred way to do it?
- Assignment in constructor:
// https://tonicdev.com/marionebl/5755b612c91caa1300f72617
...
this.bar = this.bar.bind(this);
...
- Tool-facilitated assignment in constructor
https://tonicdev.com/marionebl/5755b612c91caa1300f72617
import autobind from '...';
...
autobind(this);
...
- Class properties (needs additional experimental babel plugins)
...
bar = () => {
return this.__barMessage;
}
...
- An autobind decorator (needs experimental/disabled decorator babel plugin)
@autobind()
class Foo {
...
}