Automatically bind methods to their class instance
JavaScript
Latest commit 4cc10fe Jan 13, 2017 @sindresorhus 1.0.0
Permalink
Failed to load latest commit information.
.editorconfig init Aug 9, 2016
.gitattributes ES2015ify and require Node.js 4 Jan 13, 2017
.gitignore init Aug 9, 2016
.travis.yml ES2015ify and require Node.js 4 Jan 13, 2017
index.js ES2015ify and require Node.js 4 Jan 13, 2017
license init Aug 9, 2016
package.json 1.0.0 Jan 13, 2017
readme.md ES2015ify and require Node.js 4 Jan 13, 2017
test.js init Aug 9, 2016

readme.md

auto-bind Build Status

Automatically bind methods to their class instance

Install

$ npm install --save auto-bind

Usage

const autoBind = require('auto-bind');

class Unicorn {
    constructor(name) {
        this.name = name;
        autoBind(this);
    }
    message() {
        return `${this.name} is awesome!`;
    }
}

const unicorn = new Unicorn('Rainbow');

// Grab the method off the class instance
const message = unicorn.message;

// Still bound to the class instance
message();
//=> 'Rainbow is awesome!'

// Without `autoBind(this)`, the above would have resulted in
message();
//=> Error: Cannot read property 'name' of undefined

Related

  • bind-methods - Bind all methods in an object to itself or a specified context

License

MIT © Sindre Sorhus