Search code examples
javascriptclassprivatepublic

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!


Solution

  • 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.