Private methods in object literal?

heys all i have something like this:

var o = {
	f1:function(a) {
		return 123+f3(a);
	}
	,
	f2:function(a) {
		return 246+f3(a);
	}
	,
	f3:function(a) {
		return a*10;
	}
};

which works, but i need f3 to be private… and f1() and f2() must be able to call f3, is that possible?

Here it is simplified about as far as it can go.



var o = function () {
    function f1 (a) {
        return 123 + f3(a);
    }
    function f2 (a) {
        return 246 + f3(a);
    }
    function f3 (a) {
        return a * 10;
    }
    return {
        f1: f1,
        f2: f2
    };
}();

That can’t be done as an object literal, but it can be done as a constructor.


function O () {
    var f1 = function f1 (a) {
        return 123 + f3(a);
    }
    var f2 = function f2 (a) {
        return 246 + f3(a);
    }
    var f3 = function f3 (a) {
        return a*10;
    }
    this.f1 = f1;
    this.f2 = f2;
}
var o = new O();

o.f1() and o.f2() are public, but o.f3() remains private.

A quick look over something like http://www.crockford.com/javascript/private.html coud be useful too.

heys that’s cool. however the problem is that i do not wish to expose the class name O as well, that’s why i need the object literal. i’ve read somewhere that i could wrap this entire function O () {… as an anonymous function within the object literal declaration but i could not get this to work out. does anyone know the syntax for it?

Object literals are purely public.

You could instantiate an anonymous function which returns the function to be applied back on to the object. The function retains the scope of its parent, so it knows about the f3 function, but cannot access it directly.

You could also declare window.o and then have the init function overwrite window.o with the updated object.

There are also a few other techniques that can be used, but ultimately you will not be capable of hiding f3 until you remove it from the web browser itself, by keeping it behind some server-side code for example.

Code follows in the next post.