function Foo() {
    var myPrivateBool = false,
        myOtherVar;
    this.bar = function(myOtherVar) {
        myPrivateBool = true;
        myOtherVar = myOtherVar; // ?????????????????
    };
}
How can I set the private variable myOtherVar?
Give the parameter a different name:
    function Foo() {
        var myPrivateBool = false,
            myOtherVar;
        this.bar = function( param ) {
            myPrivateBool = true;
            myOtherVar = param;
        };
        this.baz = function() {
            alert( myOtherVar );
        };
    }
var inst = new Foo;
inst.bar( "new value" );
inst.baz();  // alerts the value of the variable "myOtherVar"
http://jsfiddle.net/efqVW/
Or create a private function to set the value if you prefer.
function Foo() {
    var myPrivateBool = false,
        myOtherVar;
    function setMyOtherVar( v ) {
        myOtherVar = v;
    }
    this.bar = function(myOtherVar) {
        myPrivateBool = true;
        setMyOtherVar( myOtherVar );
    };
    this.baz = function() {
        alert(myOtherVar);
    };
}
var inst = new Foo;
inst.bar("new value");
inst.baz();
http://jsfiddle.net/efqVW/1/
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