There is no such thing as private in JS, but you can play with scopes using the closures.
Let's say for instance that in your example you don't need to expose var1 as public property. You could easily rewrite your code as the follows:
function ctest() {
var var1 = "haha";
this.func1 = function() {
alert(var1);
func2();
alert(var1);
}
var func2 = function() {
var1 = "huhu";
}
}
Because both func1 and func2 shares the same scope – they are defined in the same function, ctest – they can access to the same variables. Of course in that case you don't have var1 exposed, so: myobj.var1 will be undefined.
If you want var1 to be exposed as property, then what you need is bind func2 to the object instance you created in the constructor:
function ctest() {
this.var1 = "haha";
this.func1 = function() {
alert(this.var1);
func2();
alert(this.var1);
}
var func2 = function() {
this.var1 = "huhu";
}.bind(this);
}
Otherwise func2 will have a different context object (this). If the browser doesn't support bind and you don't want use a shim (as shown in the link above), you can take advantage of the closures again:
function ctest() {
this.var1 = "haha";
this.func1 = function() {
alert(this.var1);
func2();
alert(this.var1);
}
var context = this;
var func2 = function() {
context.var1 = "huhu";
}
}
IMVHO is less elegant.
privatehere.obj.func1()should presumably bemyobj.func1()thisworks.