Задать закрытую переменную Javascript с тем же именем, что и у параметра функции? - PullRequest
5 голосов
/ 14 февраля 2011
function Foo() {
    var myPrivateBool = false,
        myOtherVar;
    this.bar = function(myOtherVar) {
        myPrivateBool = true;
        myOtherVar = myOtherVar; // ?????????????????
    };
}

Как установить личную переменную myOtherVar?

Ответы [ 4 ]

3 голосов
/ 14 февраля 2011

Дайте параметру другое имя:

    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/


Или создайте приватную функцию для установки значения, если хотите.

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/

0 голосов
/ 02 октября 2015

Может быть, вы можете объявить myOtherVar как MyOtherVar, используя чувствительность к регистру JavaScript, а затем назначить MyOtherVar = myOtherVar в функцию:

function Foo() {
    var MyPrivateBool = false,
        MyOtherVar;
    this.bar = function(myOtherVar) {
        MyPrivateBool = true;
        MyOtherVar = myOtherVar;
    };
}
0 голосов
/ 14 февраля 2011

Я думаю this.myOthervar = myOtherVar;повредит глобальное пространство имен и создаст переменную window.myOtherVar в объекте окна

0 голосов
/ 14 февраля 2011

Попробуйте this.myOtherVar = myOtherVar;

...