Skip to content

Instantly share code, notes, and snippets.

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