Skip to content

Instantly share code, notes, and snippets.

@eldoy
Last active July 4, 2018 13:24
Show Gist options
  • Save eldoy/2549c2fefec2530add869d64ee4343ac to your computer and use it in GitHub Desktop.
Save eldoy/2549c2fefec2530add869d64ee4343ac to your computer and use it in GitHub Desktop.
Automatically bind all function to itself from constructor of a class
// Usage: inside the constructor of a class do util.autobind(this)
const util = {}
// Binds the object instance functions to itself
util.autobind = (obj) => {
const prototype = Object.getPrototypeOf(obj)
const props = Object.getOwnPropertyNames(prototype)
for (const name of props) {
const value = prototype[name]
if (typeof value === 'function') {
obj[name] = prototype[name].bind(obj)
}
}
}
export default util
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment