Skip to content

atlassubbed/atlas-bind-methods

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

atlas-bind-methods

Binds an instance's prototype methods to itself.

Travis


install

npm install --save atlas-bind-methods

why

Suppose you have a class which uses instance variables in its methods:

// Animal.js
module.exports = class Animal {
  constructor(sound){
    this.sound = sound;
  }
  rawr(){
    console.log(this.sound)
  }
}

Normally, the following won't work:

const Animal = require("./Animal");
const cat = new Animal("meow!");
const rawr = cat.rawr;
rawr(); // TypeError: Cannot read property 'sound' of undefined

It fails because the reference loses the method's context, but you already knew that! The fix is pretty simple -- just bind the function to the instance:

...
const rawr = cat.rawr.bind(cat)
rawr() // meow!

But, this is kind of annoying when I have to do this for many methods. With this package, we can do all of the binding without cluttering our business logic.

examples

inline

const Animal = require("./Animal");
const bind = require("atlas-bind-methods");
const cat = bind(new Animal("meow!"));
const rawr = cat.rawr;
rawr() // meow!

as a side-effect

...
const cat = new Animal("meow!");
bind(cat);
const rawr = cat.rawr;
rawr() // meow!

caveats

This doesn't support subclassing, so it would only pre-bind the prototype methods of the direct constructor which is used to instantiate the object.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published