class declaration creates a new class with a given name using prototype-based inheritance.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
You can also define a class using a
class expression
. But unlike a class expression, a class declaration doesn't allow an existing class to be declared again and will throw a
SyntaxError
if attempted.
class name [extends otherName] {
// class body
}
The class body of a class declaration is executed in
严格模式
。
构造函数
method is optional.
Class declarations are not hoisted (unlike 函数声明 ).
In the following example, we first define a class named
Polygon
, then extend it to create a class named
Square
.
注意,
super()
, used in the
构造函数
, can only be used in constructors, and
must
be called
before
the
this
keyword can be used.
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(length) {
super(length, length);
this.name = 'Square';
}
}
Re-declaring a class using the class declaration throws a
SyntaxError
.
class Foo {};
class Foo {}; // Uncaught SyntaxError: Identifier 'Foo' has already been declared
The same error is thrown when a class has been defined before using the class expression.
let Foo = class {};
class Foo {}; // Uncaught SyntaxError: Identifier 'Foo' has already been declared
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'Class definitions' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
class
|
Chrome
49
|
Edge 13 | Firefox 45 | IE No |
Opera
36
|
Safari 10.1 |
WebView Android
49
|
Chrome Android
49
|
Firefox Android 45 |
Opera Android
36
|
Safari iOS 10.3 |
Samsung Internet Android
5.0
|
nodejs 6.0.0 |
完整支持
不支持
见实现注意事项。
用户必须明确启用此特征。