I am essentially trying to set a function’s prototype within the function itself. The purpose is to hide many functions inside one public function, yet keep the functionality.
Here is the non-working code in a jsFiddle. The intended behaviour is displaying “Greetings!” and “Take me to your leader.”
The code can be ‘fixed’ by moving the Outer.prototype lines and the Extensions function out of the Outer function to the global scope. However, this means the Extensions function is public and free for direct use, which it shouldn’t be.
What would be a good way to achieve this ‘private’ behaviour?
This does not work because you are overriding the prototype. When you call
new Outer, thenthiswill inherit from the currentOuter.prototype. You are then overridingObject.prototypeinside the function, but it does not affect the currently created instance, only future ones.You’d have to extend the existing prototype.
But if you want hide certain functions, use a self-invoking function:
Here,
Extensionsis defined inside the immediately executed function. Therefore it is not accessible from the outside. OnlyOutercan be accessed since you return it from that function.See this answer for a very good explanation of inheritance done right in JavaScript.