Last active
November 14, 2019 21:35
-
-
Save FlorianGoussin/f85e00b515352e59afc14c98c5de948f to your computer and use it in GitHub Desktop.
Bind private functions to this
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
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better if Symbol is supported: https://medium.com/@davidrhyswhite/private-members-in-es6-db1ccd6128a5
https://gist.github.com/davidrhyswhite/84eb4f0295c402c5546a