Kendall Frey
Kendall Frey

Reputation: 44384

Setting function's prototype to a private variable

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?

Upvotes: 0

Views: 73

Answers (1)

Felix Kling
Felix Kling

Reputation: 817238

This does not work because you are overriding the prototype. When you call new Outer, then this will inherit from the current Outer.prototype. You are then overriding Object.prototype inside 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:

var Outer = (function() {

    function Extensions() {
    }
    Extensions.protoype.Greet = function () {
        alert(this.Greetings);
    }

    function Inner() {
        Extensions.call(this);
        this.Greetings = "Take me to your leader.";
    }
    Inner.prototype = Object.create(Extensions.prototype);
    Inner.prototype.constructor = Inner;

    function Outer() {
        Extensions.call(this);
        this.Greetings = "Greetings!";
    }
    Outer.prototype = Object.create(Extensions.prototype);
    Outer.prototype.constructor = Outer;

    Outer.prototype.getInner = function() {
        return new Inner();
    };

    return Outer;

}());

Here, Extensions is defined inside the immediately executed function. Therefore it is not accessible from the outside. Only Outer can be accessed since you return it from that function.

See this answer for a very good explanation of inheritance done right in JavaScript.

Upvotes: 1

Related Questions