Repository
Current version released
6 years ago
auto-bind 
Automatically bind methods to their class instance
Install
$ npm install --save auto-bindUsage
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 undefinedRelated
- bind-methods - Bind all methods in an object to itself or a specified context
License
MIT Β© Sindre Sorhus