JavaScript instance functions versus prototype functions [duplicate]

You can actually add another level of privilege via wrapping the whole thing in a self-executing function:

var MyObj = (function() { // scoping
    var privateSharedVar="foo";

    function privateSharedFunction() {
        // has access to privateSharedVar
        // may also access publicSharedVar via explicit MyObj.prototype
        // can't be called via this
    }

    function MyObj() { // constructor
        var privateInstanceVar="bar";
        this.publicInstanceVar="baz";

        function privateInstanceFunction() {
            // has access to all vars
            // can't be called via this
        };

        this.publicInstanceMethod = function() {
            // has access to all vars
            // also known as a privileged method
        };
    }

    MyObj.prototype.publicSharedVar="quux";

    MyObj.prototype.publicSharedMethod = function() {
        // has access to shared and public vars
        // canonical way for method creation:
        // try to use this as much as possible
    };

    return MyObj;
})();

Only ‘public’ properties can be accessed from outside via this.

For performance reasons, you should avoid what I called ‘instance’ methods: For each of these, a new function object must be created for each MyObject instance, whereas there’s only a single function object per ‘shared’ method.

Leave a Comment