Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Javascript Private Variable with the same name as a Function Parameter?

function Foo() {
    var myPrivateBool = false,
        myOtherVar;
    this.bar = function(myOtherVar) {
        myPrivateBool = true;
        myOtherVar = myOtherVar; // ?????????????????
    };
}

How can I set the private variable myOtherVar?

like image 445
Garrett Avatar asked Nov 27 '22 12:11

Garrett


1 Answers

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/

like image 130
user113716 Avatar answered Dec 11 '22 03:12

user113716