Search code examples
javascriptmodule-patternprivate-methods

Private Method in Module Pattern: TypeError: undefined is not a function


I am trying to implement a classic Module Pattern in javascript, discussed here and here. But my private methods are not working. I have the following bit of testing code.

var jsStuff = (function() {

    // Private
    var sayStuffPrivate = function ( stuff ) {
        console.log( "I am a private method: " +  stuff );
        return true;
    };

    // Public
    return {
        sayStuff: function ( stuff ) {
            console.log( "I am a public method: " + stuff );
            this.sayStuffPrivate( stuff );
            return true;
        }
    }
}());

When I try to run this, I get the following:

> jsStuff.sayStuff('blah');
test.js:16 I am a public method: blah
test.js:17 Uncaught TypeError: undefined is not a function

What am I missing here?


Solution

  • this.sayStuffPrivate( stuff );
    

    Here, this refers to the object you actually returned from the sayStuff function. That doesn't have a property called sayStuffPrivate in it. So, this.sayStuffPrivate will be evaluated to undefined and since you are using that as a function, it fails with that error.

    You are supposed to take advantage of the closure property and invoke it like this

    sayStuffPrivate( stuff );