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

如何设置私有(private)变量 myOtherVar?

最佳答案

给参数一个不同的名字:

    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/

或者,如果您愿意,可以创建一个私有(private)函数来设置该值。
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/

10-06 00:25