Skip to main content

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
  • bind-methods - Bind all methods in an object to itself or a specified context

License

MIT Β© Sindre Sorhus