Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript private function access public variable

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!

like image 259
MirrorMirror Avatar asked May 23 '12 11:05

MirrorMirror


2 Answers

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.

like image 145
Alnitak Avatar answered Sep 23 '22 21:09

Alnitak


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";
    }
}
like image 45
Lucero Avatar answered Sep 24 '22 21:09

Lucero