Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Unbound methods, interest in autobinding? #345

Closed
@marionebl

Description

@marionebl

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.

  1. Are you interested in a PR that auto binds all methods?
  2. 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 {
...
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions