JavaScript 中的静态变量

新手上路,请多包涵

如何在 Javascript 中创建静态变量?

原文由 Rajat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

如果您来自基于类的、静态类型的面向对象语言 (如 Java、C++ 或 C#) ,我假设您正在尝试创建与“类型”相关联的变量或方法,而不是与实例相关联的变量或方法。

使用带有构造函数的“经典”方法的示例可能可以帮助您了解基本 OO JavaScript 的概念:

 function MyClass () { // constructor function
 var privateVariable = "foo"; // Private variable

 this.publicVariable = "bar"; // Public variable

 this.privilegedMethod = function () { // Public Method
 alert(privateVariable);
 };
 }

 // Instance method will be available to all instances but only load once in memory
 MyClass.prototype.publicMethod = function () {
 alert(this.publicVariable);
 };

 // Static variable shared by all instances
 MyClass.staticProperty = "baz";

 var myInstance = new MyClass();

staticProperty 定义在 MyClass 对象(它是一个函数)中,与其创建的实例无关,JavaScript 将函数视为 一等对象,因此作为对象,您可以将属性分配给函数。

更新: ES6 引入了通过 class 关键字 声明类 的能力。它是现有基于原型的继承的语法糖。

static 关键字 允许您轻松地在类中定义静态属性或方法。

让我们看看上面用 ES6 类实现的例子:

 class MyClass {
 // class constructor, equivalent to
 // the function body of a constructor
 constructor() {
 const privateVariable = 'private value'; // Private variable at the constructor scope
 this.publicVariable = 'public value'; // Public property

 this.privilegedMethod = function() {
 // Public Method with access to the constructor scope variables
 console.log(privateVariable);
 };
 }

 // Prototype methods:
 publicMethod() {
 console.log(this.publicVariable);
 }

 // Static properties shared by all instances
 static staticProperty = 'static value';

 static staticMethod() {
 console.log(this.staticProperty);
 }
 }

 // We can add properties to the class prototype
 MyClass.prototype.additionalMethod = function() {
 console.log(this.publicVariable);
 };

 var myInstance = new MyClass();
 myInstance.publicMethod(); // "public value"
 myInstance.additionalMethod(); // "public value"
 myInstance.privilegedMethod(); // "private value"
 MyClass.staticMethod(); // "static value"

原文由 Christian C. Salvadó 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可能会利用 JS 函数也是对象这一事实——这意味着它们可以具有属性。

例如,引用(现已消失)文章 Static variables in Javascript 中 给出的示例:

 function countMyself() {
    // Check to see if the counter has been initialized
    if ( typeof countMyself.counter == 'undefined' ) {
        // It has not... perform the initialization
        countMyself.counter = 0;
    }

    // Do something stupid to indicate the value
    alert(++countMyself.counter);
}

如果多次调用该函数,您会看到计数器正在递增。

这可能是比用全局变量污染全局命名空间更好的解决方案。

这是另一种可能的解决方案,基于闭包: Trick to use static variables in javascript

 var uniqueID = (function() {
   var id = 0; // This is the private persistent value
   // The outer function returns a nested function that has access
   // to the persistent value.  It is this nested function we're storing
   // in the variable uniqueID above.
   return function() { return id++; };  // Return and increment
})(); // Invoke the outer function after defining it.

这会得到相同类型的结果——除了这次,增加的值被返回,而不是被显示。

原文由 Pascal MARTIN 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题