简体   繁体   中英

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?

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/

In JavaScript it is a convention to prefix the name of private variables with an _ (underscore). Following this convention you can change your code to.

function Foo() {
    var _myPrivateBool = false,_myOtherVar;
    this.bar = function(myOtherVar) {
        _myPrivateBool = true;
        _myOtherVar = myOtherVar;
    };
}

In the above code we are assigning the local variable myOtherVar to the private variable _myOtherVar. This way it looks like we have the same name for the private and local variables.

Note:This is just a convention followed.Prefixing a variable name with _ does not make it a private variable.

I think this.myOthervar = myOtherVar; will corrupt the global namespace and created a variable window.myOtherVar in window object

Maybe you can declare myOtherVar as MyOtherVar, taking advantage of javascript's case sensitiveness, then assign MyOtherVar=myOtherVar into the function:

function Foo() {
    var MyPrivateBool = false,
        MyOtherVar;
    this.bar = function(myOtherVar) {
        MyPrivateBool = true;
        MyOtherVar = myOtherVar;
    };
}

试试this.myOtherVar = myOtherVar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM