本文介绍了JavaScript 中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I create static variables in Javascript?

推荐答案

如果您来自基于类的、静态类型的面向对象语言(如 Java、C++ 或 C#),我认为您正在尝试创建与类型"关联但与实例关联的变量或方法.

If you come from a class-based, statically typed object-oriented language (like Java, C++ or C#) I assume that you are trying to create a variable or method associated to a "type" but not to an instance.

使用经典"方法和构造函数的示例可能会帮助您了解基本 OO JavaScript 的概念:

An example using a "classical" approach, with constructor functions maybe could help you to catch the concepts of basic 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 将函数视为 一级对象,因此作为一个对象,您可以为函数分配属性.

staticProperty is defined in the MyClass object (which is a function) and has nothing to do with its created instances, JavaScript treats functions as first-class objects, so being an object, you can assign properties to a function.

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

UPDATE: ES6 introduced the ability to declare classes through the class keyword. It is syntax sugar over the existing prototype-based inheritance.

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

The static keyword allows you to easily define static properties or methods in a class.

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

Let's see the above example implemented with ES6 classes:

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"

这篇关于JavaScript 中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:37