Skip to content

Instantly share code, notes, and snippets.

@ajmas
Created May 29, 2019 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajmas/74bc3ff48dcd0c645d3fd59f953e8b2c to your computer and use it in GitHub Desktop.
Save ajmas/74bc3ff48dcd0c645d3fd59f953e8b2c to your computer and use it in GitHub Desktop.
Method to autobind methods in NodeJS
// Based logic on example for discovering properties here: https://stackoverflow.com/questions/31054910/get-functions-methods-of-a-class
// This takes a class instance and returns an object with the objects bound to the instance
// Written, mainly to see if it could be done to avoid having to do individual explcit binds when
// registering with express router
function autoBind(instance) {
let obj = instance;
let props = []
do {
const l = Object.getOwnPropertyNames(obj)
.concat(Object.getOwnPropertySymbols(obj).map(s => s.toString()))
.sort()
.filter((p, i, arr) =>
typeof obj[p] === 'function' && //only the methods
p !== 'constructor' && //not the constructor
(i == 0 || p !== arr[i - 1]) && //not overriding in this prototype
props.indexOf(p) === -1 //not overridden in a child
)
props = props.concat(l)
}
while (
(obj = Object.getPrototypeOf(obj)) && //walk-up the prototype chain
Object.getPrototypeOf(obj) //not the the Object prototype methods (hasOwnProperty, etc...)
)
const autoboundObj = {};
props.forEach((prop) => {
autoboundObj[prop] = instance[prop].bind(instance);
});
return autoboundObj;
}
export default autoBind;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment