Skip to content

Instantly share code, notes, and snippets.

@ajmas ajmas/autobind.js
Created May 29, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.