在类方法之外声明类属性 [英] Declare a class property outside of a class method
问题描述
看看 x 和 y 是如何在构造函数中声明的:
class 点 {构造函数(x,y){this.x = x;这.y = y;}toString() {return '(' + this.x + ', ' + this.y + ')';}}
有没有办法在函数之外声明属性,例如:
class 点 {//在这里声明静态类属性//a: 22构造函数(x,y){this.x = x;这.y = y;}toString() {return '(' + this.x + ', ' + this.y + ')';}}
所以我想将 a 分配给 22,但我不确定我是否可以在构造函数之外但仍然在类中执行此操作..
直接在 ES6 中的类上初始化属性是
See how x and y are declared in constructor:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
is there an way to declare properties outside of functions for instance:
class Point {
// Declare static class property here
// a: 22
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
So I want to assign a to 22 but I am unsure if i can do it outside the constructor but still inside the class..
Initializing properties directly on a class in ES6 is not possible, only methods can currently be declared in this way. Same rules stand in ES7 as well.
However, it is a proposed feature that might come after ES7 (currently in stage 3). Here is the official proposal.
Additionally, the syntax the proposal is suggesting is slightly different (=
instead of :
):
class Point {
// Declare class property
a = 22
// Declare class static property
static b = 33
}
If you are using Babel, you can use the stage 3 settings to enable this feature.
The other way to do this in ES6, other than in the constructor, is to do it after the class definition:
class Point {
// ...
}
// Declare class property
Point.prototype.a = 22;
// Declare class static property
Point.b = 33;
Here's a good SO Thread diving into this topic some more
Note:
As Bergi mentioned in the comments, the suggested syntax:
class Point {
// Declare class property
a = 22
}
is just syntactic sugar to provide a shortcut for this code:
class Point {
constructor() {
this.a = 22;
}
}
Where both of those statements assign a property to an instance.
However, this isn't exactly the same as assigning to the prototype:
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
Both would still be available via an instance:
var point = new Point();
p.a // 22
p.b // 33
But getting b
would require going up the prototype chain while a
is available directly on the object.
这篇关于在类方法之外声明类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!