Static variables in JavaScript

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

How can I create static variables in Javascript?

30条回答
  •  你的背包
    2020-11-22 02:25

    There are 4 ways to emulate function-local static variables in Javascript.

    Method 1: Using function object properties (supported in old browsers)

    function someFunc1(){
        if( !('staticVar' in someFunc1) )
            someFunc1.staticVar = 0 ;
        alert(++someFunc1.staticVar) ;
    }
    
    someFunc1() ; //prints 1
    someFunc1() ; //prints 2
    someFunc1() ; //prints 3
    

    Method 2: Using a closure, variant 1 (supported in old browsers)

    var someFunc2 = (function(){
        var staticVar = 0 ;
        return function(){
            alert(++staticVar) ;
        }
    })()
    
    someFunc2() ; //prints 1
    someFunc2() ; //prints 2
    someFunc2() ; //prints 3
    

    Method 3: Using a closure, variant 2 (also supported in old browsers)

    var someFunc3 ;
    with({staticVar:0})
        var someFunc3 = function(){
            alert(++staticVar) ;
        }
    
    someFunc3() ; //prints 1
    someFunc3() ; //prints 2
    someFunc3() ; //prints 3
    

    Method 4: Using a closure, variant 3 (requires support for EcmaScript 2015)

    {
        let staticVar = 0 ;
        function someFunc4(){
            alert(++staticVar) ;
        }
    }
    
    someFunc4() ; //prints 1
    someFunc4() ; //prints 2
    someFunc4() ; //prints 3
    

提交回复
热议问题