1

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?

Dave
  • 822
  • 1
  • 7
  • 17
  • It's not a method, as that would mean it's no more private. It's just a local function, and should be accessed as such; not via `this.` like a public property of your object. – Bergi Dec 11 '14 at 06:06
  • Note that the value of *this* within a function is determined entirely by how you call the function (or by using *bind*), not lexically (or how the function was created). – RobG Dec 11 '14 at 06:17

2 Answers2

3
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 );
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Thanks! I'm new to js, and it seems such a subtle thing. Obvious, I guess, once you've seen it a few times. – Dave Dec 11 '14 at 06:14
  • Incidentally, can private methods call the public ones? If so, how? – Dave Dec 11 '14 at 06:29
  • This answered my second question (Can private methods call the public ones?): http://stackoverflow.com/questions/4505073/how-can-i-call-a-public-method-from-within-a-private-one-when-using-the-javascri?rq=1 – Dave Dec 11 '14 at 06:38
0

You should call sayStuffPrivate without this. Try This:

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 );
            sayStuffPrivate( stuff );
            return true;
        }
    }
}());