I have a third-party library that exposes a public method that points to a private one.
const thirdPartyLibrary = function(){
function privateFunction() {
return superSecretFunction();
};
function superSecretFunction() {
return Math.random();
};
// library public api
return {
publicMethod:() => { return privateFunction() }
}
}();
I've simplified it a bit in the example, but it's something like an implementation of the Module Pattern.
I wonder if it is possible to somehow access these private methods to change their behavior or at least to expose them.
I have tried to access this
but as expected the private methods are not listed.
thirdPartyLibrary.foo = function(){console.log(this)};
thirdPartyLibrary.foo() // private members not listed
Obviously, I cannot change the library's code :)
No, it is not possible. Closure-scoped variables really are private.
All you can do is access (and overwrite) the methods of the thirdPartyLibrary
object, which is created by the "library public api" object literal. This means you can completely replace the whole library with your own version if you need to, but you cannot access its internals1.
1: Some libraries accidentally leak their internals, e.g. by calling callbacks with an internal as the this
context, but that's a bug in the module implementation.