【问题标题】:Javascript local static variableJavascript局部静态变量
【发布时间】:2018-08-02 01:03:35
【问题描述】:

不确定我是否完全理解我在此处找到的类似问题的答案,因此请务必确定:

我想在函数中有一个局部变量,只初始化一次(类似于 C、C++ 等强类型语言中的静态变量)。

当然,我可以全局声明它,但将它放在该函数的范围内似乎更好,因为它不会在其他任何地方使用。

现在,这就是我要做的:

function func(data) {
    func.PARAMS = [
        {"name": "from", "size": 160, "indexed": true},
        {"name": "input", "size": 256, "indexed": false},
        {"name": "output", "size": 256, "indexed": false},
    ];
    ...
}

我的问题是,func.PARAMS 确实会被初始化一次,还是会在每次调用函数时都被初始化?

根据我找到的一些答案(例如this one),我需要在初始化之前添加如下内容:

if (typeof func.PARAMS == 'undefined')

当然,这种“补充”在强类型语言中是无关紧要的,所以我只想确定它是绝对必要的,以确保“静态行为”(即一次性初始化)。

【问题讨论】:

  • 是的,如果不检查typeof func.PARAMS == 'undefined',根据func,每次调用funct时都会设置PARAMS

标签: javascript static static-variables


【解决方案1】:

除了使用函数对象的属性(如您在示例中所做的那样)之外,还有 3 种其他方法可以在 Javascript 中模拟函数局部静态变量。

它们都依赖于闭包,但使用不同的语法。

方法一(旧浏览器支持):

var someFunc1 = (function(){
    var staticVar = 0 ;
    return function(){
        alert(++staticVar) ;
    }
})() ;

someFunc1() ; //prints 1
someFunc1() ; //prints 2
someFunc1() ; //prints 3

方法2(旧浏览器也支持):

var someFunc2 ;
with({staticVar:0})
    var someFunc2 = function(){
        alert(++staticVar) ;
    } ;

someFunc2() ; //prints 1
someFunc2() ; //prints 2
someFunc2() ; //prints 3

方法 3(需要支持 EcmaScript 2015):

{
    let staticVar = 0 ;
    function someFunc3(){
        alert(++staticVar) ;
    }
}

someFunc3() ; //prints 1
someFunc3() ; //prints 2
someFunc3() ; //prints 3

strict mode 的方法 3:

'use strict'
{
    let staticVar = 0 ;
    var someFunc3 = function(){
        alert(++staticVar) ;
    } ;
}

someFunc3() ; //prints 1
someFunc3() ; //prints 2
someFunc3() ; //prints 3

【讨论】:

  • 我尝试了方法 3 并且(如预期的那样)得到 someFunc3() is undefined...
  • @PeteLomax,您可能正在使用严格模式。查看答案更新。
  • 我的错误,已删除
【解决方案2】:

JavaScript 可能看起来与 C++ 相似,但实际上却大不相同。最初,它是为浏览器中的简单任务而设计的。为了模仿 JS 程序员中类似 C++ 的功能,需要创建复杂的结构。例如,在 ES6 中现在有类,但实际上,它们只是依赖于原型继承的构造函数的语法糖。在 ES6 中,您现在可能需要检查静态方法。

我想在你的情况下,最好使用更像 C# 并且是 JavaScript 超集的 TypeScript。

【讨论】:

    【解决方案3】:

    虽然 Javascript 本身没有静态变量的概念,但很容易模拟它们。对象的一种模式是使用闭包(通过自调用函数)。

    const MyClass = ( function() {
    
        // Static variables are in the scope of the self-invoking function
    
        const _myStaticVariable = 'this is a static variable';
          let _instances = 0; // this is also a class variable
    
        // The constructor function is returned to MyClass, but still has the static variables in scope
    
        return function() {
    
            _instances++;
    
            this.sayStaticVariable = function(){
                console.log(_myStaticVariable);
            }
    
            this.howMany = function(){
                console.log(_instances);
            }
        }
    
    })();
    
    myInstance = new MyClass();
    
    myInstance.sayStaticVariable();
    // this is a static variable
    
    myInstance.howMany();
    // 1
    

    在这种情况下,_myStaticVariable_instances 只会被初始化一次,但仍会在返回给 MyClass 的构造函数的范围内(并可访问)。

    您似乎在询问函数上下文中的静态变量而不是对象,您可能可以使用函数组合来适应这种模式

    【讨论】:

      【解决方案4】:

      每次调用函数时都会分配它。 JavaScript 中没有 static 变量。您需要在函数之外声明它们。不过,您可以在本地范围内执行此操作:

      var func;
      {
          const PARAMS = [
              {"name": "from", "size": 160, "indexed": true},
              {"name": "input", "size": 256, "indexed": false},
              {"name": "output", "size": 256, "indexed": false},
          ];
          func = function(data) {
              …
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-04
        • 2012-06-06
        • 1970-01-01
        • 2018-04-18
        • 1970-01-01
        相关资源
        最近更新 更多