在类方法外声明一个类属性

28

看一下构造函数中如何声明x和y:

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

有没有一种方法可以在函数之外声明属性,例如:

class Point {
  // Declare static class property here
  // a: 22
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

所以我想把a赋值为22,但我不确定是否可以在构造函数之外但仍在类内部完成。


1
我认为你可以使用 static get x(){ return 5; },这样做的效果是一样的,只是有点啰嗦。 - somethinghere
2个回答

44

在ES6中,直接在类上初始化属性是不可能的,只有方法可以以这种方式声明。ES7也遵循同样的规则。

然而,这是一个提议中的功能,可能会在ES7之后实现(目前处于第三阶段)。这是官方提案

此外,该提案建议的语法略有不同(使用=代替:):

class Point {
  // Declare class property
  a = 22
  // Declare class static property
  static b = 33
}

如果您正在使用Babel,您可以使用阶段3设置来启用此功能。 这里是一个Babel REPL示例
除了在构造函数中之外,在ES6中另一种方法是在类定义之后进行如下操作:
class Point {
  // ...
}

// Declare class property
Point.prototype.a = 22;

// Declare class static property
Point.b = 33;

这里有一个好的SO讨论串,更深入地探讨了这个主题


注意:

如评论中Bergi所提到的,建议使用的语法为:

class Point {
  // Declare class property
  a = 22
}

"

只是一种语法糖,提供了一个快捷方式来代替这段代码:

"
class Point {
  constructor() {
    this.a = 22;
  }
}

带有这两个语句都会为实例分配一个属性。

然而,这与分配给原型并不完全相同:

class Point {
  constructor() {
    this.a = 22;  // this becomes a property directly on the instance
  }
}

Point.prototype.b = 33; // this becomes a property on the prototype

两者仍可通过实例访问:

var point = new Point();
p.a // 22
p.b // 33

但是获取b需要沿着原型链向上查找,而a直接在对象上可用。

enter image description here


你能不能也使用 static get x(){} 呢?只是好奇。实际上这两种方式不是一样的吗? - somethinghere
好的,它并不完全是同样的效果,但可以类似。您可以使用“get”来获取常量值或构造函数中声明的另一个值,这与声明可直接进行 get/set 操作的值不同。 - nem035
1
嗯,没错。好吧,谢天谢地这只是一些语法糖,我们总能依靠 JS 伟大的对象遗产 :) - somethinghere
2
必须喜欢它们的原型 :) - nem035
你可能需要添加这个说明,即 a = 22 不同于对原型分配,而是在构造函数中创建实例属性的一种非常令人困惑的语法糖。 - Bergi

1

@nem035是正确的,它处于提案阶段。

然而,@nem035的建议是通过类实例成员来实现的其中一种方式。

// 在此声明静态类属性

看起来你想要声明一个静态成员。如果是这样,JavaScript的方法如下:

class Point {
  // ...
}
Point.a = '22';

你实际期望的方式可以在TypeScript中完成。
class Point {
     static a = 22;
}

编译输出将与上面的示例相同。
Point.a = '22';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接