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

问题描述 投票:15回答:2

了解如何在构造函数中声明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 + ')';
  }
}

所以我想分配给22,但我不确定我是否可以在构造函数之外做但仍然在类中。

javascript ecmascript-6
2个回答
24
投票

直接在ES6中的类上初始化属性是not possible,目前只能以这种方式声明方法。同样的规则也适用于ES7。

但是,这是一个建议的功能,可能会在ES7之后(目前处于第3阶段)。这是official proposal

此外,该提案建议的语法是slightly different=而不是:):

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

如果您使用的是Babel,则可以使用第3阶段设置启用此功能。

Here's a Babel REPL example


除了构造函数之外,在ES6中执行此操作的另一种方法是在类定义之后执行此操作:

class Point {
  // ...
}

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

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

这是一个good SO Thread潜入这个主题更多


注意:

正如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


1
投票

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

但是,@ nem035的sugggetion是实现它作为类实例成员的一种方法。

//在这里声明静态类属性

似乎你想要声明一个静态成员。如果是,JavaScript方式是

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

您实际期望的方式可以在TypeScript中完成

class Point {
     static a = 22;
}

编译后的输出与上例相同

Point.a = '22';
© www.soinside.com 2019 - 2024. All rights reserved.