现代方法为Javascript类创建静态或类变量 [英] Modern way to create static or Class variable for Javascript class

查看:198
本文介绍了现代方法为Javascript类创建静态或类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一个明确的答案,大多数弹出仍然涉及旧的(或我应该说传统)的方式使用 function

I've been hunting around for a clear answer to this, and most of what pops up still relates to the old (or should I say "traditional") way of defining classes using function.

根据此SO回答


ES2015不支持类属性。

Class properties are not supported in ES2015.


$ b b

据我所知,向类添加静态变量的唯一方法是:

As far as I can tell, the only way to add a static variable to a class is like:

https://jsfiddle.net/abalter/fknwx3n4/

class C {

  constructor(x) {
    console.log("in constructor " + x);
    this.x = x;
    this.add(this.x);
  }

  add(x) {
    console.log("in add " + x);
    C.alist.push(x);
  }

  show() {
    console.log("in show");
    console.log(C.alist);
  }
}

// MUST be done outside of actual class definition.
C.alist = [];

c1 = new C(5);
c1.show();
c2 = new C(10);
c1.show();
c2.show();

这是故事的结尾吗?

推荐答案

你可以调用一个静态函数来初始化所有的定义类之后的静态成员,然后可选地删除该函数。 (可能重置静态变量将是一个功能?)

You could call a static function that initializes all the static members immediately after the class is defined, and then optionally delete that function. (Possibly resetting static variables would be a feature?)

这将允许您将所有静态变量保存在类声明中。 / p>

This would allow you to keep all of your static variables inside the class declaration.

class C {
  static init() {
    C.alist = [];
  }

  constructor(x) {…}
  add(x) {…}
  show() {…}
}
C.init();
delete C.init;

另一个选择是在构造函数中初始化静态变量,但这要求至少一个对象被实例化

Another option is to initialize static variables in the constructor, but this requires that at least one object be instantiated before the static variables can be used.

class C {
  constructor(x) {
    C.alist = C.alist || [];
    …
  }
  add(x) {…}
  show() {…}
}

这篇关于现代方法为Javascript类创建静态或类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆