i have this class:
function ctest() {
this.var1 = "haha";
this.func1 = function() {
alert(this.var1);
func2();
alert(this.var1);
}
var func2 = function() {
this.var1 = "huhu";
}
}
and call it :
var myobj = new ctest();
myobj.func1();
isn't supposed that the second alert will popup "huhu" ? func2 is private, can it not access the var1 public variable ?
if a private function cannot access a public variable, how can i do it ?
Thanks in advance!
You need to provide a context for the call to func2
:
this.func1 = function() {
alert(this.var1);
func2.call(this);
alert(this.var1);
}
Without the context the call will use the global object (i.e. window
) - you should see when you run your current code that window.var1
is getting created between the two alerts.
Functions are not tied to instances, therefore your invocation of func2
ends up as invocation without this
pointing to the expected instance.
You can either fix the invocation to include the context:
function ctest() {
this.var1 = "haha";
this.func1 = function() {
alert(this.var1);
func2.call(this);
alert(this.var1);
}
var func2 = function() {
this.var1 = "huhu";
}
}
Or you can keep a variable with the wanted object reference around:
function ctest() {
var that = this;
this.var1 = "haha";
this.func1 = function() {
alert(this.var1);
func2();
alert(this.var1);
}
var func2 = function() {
that.var1 = "huhu";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With