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

推荐答案

如果您来自基于类的静态类型的面向对象语言(like Java, C++ or C#),我假设您试图创建与"类型"关联的变量或方法,而不是与实例关联的变量或方法.

一个使用"classic "方法和构造函数的示例可能会帮助您理解基本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将函数视为first-class objects,因此作为一个对象,可以为函数分配属性.

UPDATE:ES6通过class关键字引入了到declare classes的能力.它是现有的基于原型的继承之上的语法糖.

允许您轻松地在类中定义静电属性或方法.

让我们看看上面使用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"

Javascript相关问答推荐

如何使用Echart 5.5.0创建箱形图

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

传递一个大对象以在Express布局中呈现

角色 map 集/spritebook动画,用户输入不停止在键上相位器3

使用JavaScript重新排序行

Google maps API通过API返回ZERO_RESULTS,以获得方向请求,但适用于Google maps

获取Uint8ClampedArray中像素数组的宽度/高度

我的角模板订阅后不刷新'

如何将多维数组插入到另一个多维数组中?

如何将zoom 变换应用到我的d3力有向图?

自定义图表工具提示以仅显示Y值

为什么当我更新数据库时,我的所有组件都重新呈现?

与svg相反;S getPointAtLength(D)-我想要getLengthAtPoint(x,y)

使用自动识别发出信号(&Q)

将嵌套数组的元素乘以其深度,输出一个和

如何在FiRestore中的事务中使用getCountFromServer

FindByIdAndUpdate在嵌套对象中创建_id

为什么在运行于<;img>;事件处理程序中的JavaScript中x和y是不可变的?

我如何才能获得价值观察家&对象&S的价值?

在Reaction Native中,ScrolltoIndex在结束时不一致地返回到索引0