Last active
July 4, 2018 13:24
-
-
Save eldoy/2549c2fefec2530add869d64ee4343ac to your computer and use it in GitHub Desktop.
Automatically bind all function to itself from constructor of a class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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