Search code examples
javascriptprivatejavascript-objects

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?


Solution

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