Static variables in JavaScript

后端 未结 30 2208
别那么骄傲
别那么骄傲 2020-11-22 01:55

How can I create static variables in Javascript?

30条回答
  •  隐瞒了意图╮
    2020-11-22 02:17

    You do it through an IIFE (immediately invoked function expression):

    var incr = (function () {
        var i = 1;
    
        return function () {
            return i++;
        }
    })();
    
    incr(); // returns 1
    incr(); // returns 2
    

提交回复
热议问题