JS增量变量(如果存在),否则创建新变量

时间:2016-01-25 01:14:57

标签: javascript

我想为特定用例创建一个本地函数变量,而不会污染我的全局对象范围。我将多次调用doThis(),但希望保留本地计数器值。

所以,这样做:

TaskHandler = {

     doThis : function () { 
            myVariable+= (myVariable) ? var myVariable = 0;
            doSomethingWithVariable(myVariable);

            // OR

            var myVariable = myVariable+=1 || 0;

            // OR

            var myVariable = (myVariable) ? myVariable+=1 : 0;
     }

而不是:

TaskHandler = {
     myVariable : 0,

     doThis : function () { 
            this.myVariable++;
            doSomethingWithVariable(this.myVariable);
     }

这可能吗?

TaskHandler = {

    doThis : function (requirement) {

        var track_index = (function () {
           var myVariable = 0;
           return function () {
               ++myVariable;
           }
        })();

       doSomethingWithVariable(track_index);
   },

}
    TaskHandler = {

        doThis : function () {

         (function () {
            console.log('called'); // This is called
            var myVariable = 0;
            return function () {
                ++myVariable;
                console.log(myVariable); // This is NOT called
            }
        })();
   }
}

上次修改:

TaskHandler = {

    someFunction : function (myObject) {

        this.doThis(myObject).counter();
    },

    doThis : function (myObject) {

         return {
            counter : (function (myObject) {
                var myVariable = 0;
                return function () {
                    ++myVariable;
                    console.log('index', myVariable); //not incrementing
                }
            })(myObject)
        }
    }
}

3 个答案:

答案 0 :(得分:2)

你需要一个闭包:一个在局部变量范围内声明的函数,因此"记得"这个变量稍后。

例如:

TaskHandler = {

    doThis : (function () {
        var myVariable = -1;

        return function () {
            ++myVariable;
            doSomethingWithVariable(myVariable);
        };
    })(),

    // ... rest of TaskHandler's properties ...
 }

(其中(function () { ... })()an immediately-invoked function expression)。

答案 1 :(得分:0)

您可以检查值是否为undefined,如下:

TaskHandler = {
    doThis: function() {
        if (typeof this.myVariable === 'undefined') {
            this.myVariable = 0;
        }
        doSomethingWithVariable(this.myVariable);
    }
}

答案 2 :(得分:0)

您必须将var放在某处,但它不需要在全局范围内或作为对象的字段。 考虑到你在浏览器中使用普通的ES5,所以我确实排除了ES6新功能的所有细节,你可以这样做:

(function () {
  var myVariable = 0;
  window.taskHandler = {
    doThis : function () { 
      myVariable++;
      doSomethingWithVariable(myVariable);
    }
  }
})()

因此,myVariable未公开,您的全局对象未被污染"。