Skip to content

Instantly share code, notes, and snippets.

@FlorianGoussin
Last active November 14, 2019 21:35
Show Gist options
  • Save FlorianGoussin/f85e00b515352e59afc14c98c5de948f to your computer and use it in GitHub Desktop.
Save FlorianGoussin/f85e00b515352e59afc14c98c5de948f to your computer and use it in GitHub Desktop.
Bind private functions to this
function myFunc1() {
console.log(this.myProp)
}
function myFunc2() {}
const _p = {}
/**
* bind an array of functions to this
* WARNING: only works with named functions
* @param {object} instance pass the instance this
* @param {fnToBind} fnToBind array with all the function to bind to this
* @param {privatePrefix} privatePrefix prefix where all the private bound functions are
*/
const bindFunctions = (instance, fnToBind, privatePrefix) => {
fnToBind.forEach(fn => {
privatePrefix[fn.name] = fn.bind(instance)
})
}
class MyClass {
constructor(myProp) {
this.myProp = myProp
bindFunctions(this, [myFunc1, myFunc2], _p)
}
myPublicMethod() {
_p.myFunc1()
}
}
@FlorianGoussin
Copy link
Author

FlorianGoussin commented Nov 14, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment