Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 classalike semantics.
Classes are in fact "special functions ", and just as you can define function expressions and 函数声明 , the class syntax has two components: class expressions and class declarations .
One way to define a class is using a
class declaration
. To declare a class, you use the
class
keyword with the name of the class ("Rectangle" here).
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
An important difference between
函数声明
and
class declarations
is that function declarations are
hoisted
and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a
ReferenceError
:
const p = new Rectangle(); // ReferenceError
class Rectangle {}
A
class expression
is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's)
name
property, though).
// unnamed
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
console.log(Rectangle.name);
// output: "Rectangle"
// named
let Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
console.log(Rectangle.name);
// output: "Rectangle2"
注意: Class expressions are subject to the same hoisting restrictions as described in the Class declarations 章节。
The body of a class is the part that is in curly brackets
{}
. This is where you define class members, such as methods or constructor.
The body of a class is executed in 严格模式 , i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript.
constructor
method is a special method for creating and initializing an object created with a
class
. There can only be one special method with the name "constructor" in a class. A
SyntaxError
will be thrown if the class contains more than one occurrence of a
构造函数
方法。
A constructor can use the
super
keyword to call the constructor of the super class.
另请参阅 method definitions .
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100
static
keyword defines a static method for a class. Static methods are called without
instantiating
their class and
cannot
be called through a class instance. Static methods are often used to create utility functions for an application.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
p1.distance; //undefined
p2.distance; //undefined
console.log(Point.distance(p1, p2)); // 7.0710678118654755
this
with prototype and static methods
When a static or prototype method is called without a value for
this
, such as by assigning a variable to the method and then calling it, the
this
value will be
undefined
inside the method. This behavior will be the same even if the
"use strict"
directive isn't present, because code within the
class
body's syntactic boundary is always executed in strict mode.
class Animal {
speak() {
return this;
}
static eat() {
return this;
}
}
let obj = new Animal();
obj.speak(); // the Animal object
let speak = obj.speak;
speak(); // undefined
Animal.eat() // class Animal
let eat = Animal.eat;
eat(); // undefined
If we rewrite the above using traditional function-based syntax in non–strict mode, then
this
method calls is automatically bound to the initial
this
value, which by default is the
全局对象
. In strict mode, autobinding will not happen; the value of
this
remains as passed.
function Animal() { }
Animal.prototype.speak = function() {
return this;
}
Animal.eat = function() {
return this;
}
let obj = new Animal();
let speak = obj.speak;
speak(); // global object (in non–strict mode)
let eat = Animal.eat;
eat(); // global object (in non-strict mode)
Instance properties must be defined inside of class methods:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
Static (class-side) data properties and prototype data properties must be defined outside of the ClassBody declaration:
Rectangle.staticWidth = 20; Rectangle.prototype.prototypeWidth = 25;
Public and private field declarations are an experimental feature (stage 3) proposed at TC39 , the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like Babel .
With the JavaScript field declaration syntax, the above example can be written as:
class Rectangle {
height = 0;
width;
constructor(height, width) {
this.height = height;
this.width = width;
}
}
By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.
As seen above, the fields can be declared with or without a default value.
见 public class fields 了解更多信息。
Using private fields, the definition can be refined as below.
class Rectangle {
#height = 0;
#width;
constructor(height, width) {
this.#height = height;
this.#width = width;
}
}
It's an error to reference private fields from outside of the class; they can only be read or written within the class body. By defining things which are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may change version to version.
Private fields can only be declared up-front in a field declaration.
Private fields cannot be created later through assigning to them, the way that normal properties can.
更多信息,见 private class fields .
extends
extends
keyword is used in
class declarations
or
class expressions
to create a class as a child of another class.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(`${this.name} barks.`);
}
}
let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
If there is a constructor present in the subclass, it needs to first call super() before using "this".
One may also extend traditional function-based "classes":
function Animal (name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(`${this.name} makes a noise.`);
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
// For similar methods, the child's method takes precedence over parent's method
Note that classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object, you can instead use
Object.setPrototypeOf()
:
const Animal = {
speak() {
console.log(`${this.name} makes a noise.`);
}
};
class Dog {
constructor(name) {
this.name = name;
}
}
// If you do not do this you will get a TypeError when you invoke speak
Object.setPrototypeOf(Dog.prototype, Animal);
let d = new Dog('Mitzie');
d.speak(); // Mitzie makes a noise.
You might want to return
Array
objects in your derived array class
MyArray
. The species pattern lets you override default constructors.
For example, when using methods such as
map()
that returns the default constructor, you want these methods to return a parent
Array
object, instead of the
MyArray
object. The
Symbol.species
symbol lets you do this:
class MyArray extends Array {
// Overwrite species to the parent Array constructor
static get [Symbol.species]() { return Array; }
}
let a = new MyArray(1,2,3);
let mapped = a.map(x => x * x);
console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array); // true
super
super
keyword is used to call corresponding methods of super class. This is one advantage over prototype-based inheritance.
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(`${this.name} roars.`);
}
}
let l = new Lion('Fuzzy');
l.speak();
// Fuzzy makes a noise.
// Fuzzy roars.
Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.
A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:
let calculatorMixin = Base => class extends Base {
calc() { }
};
let randomizerMixin = Base => class extends Base {
randomize() { }
};
A class that uses these mix-ins can then be written like this:
class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'Class definitions' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
类
|
Chrome
49
|
Edge 13 | Firefox 45 | IE No |
Opera
36
|
Safari 9 |
WebView Android
49
|
Chrome Android
49
|
Firefox Android 45 |
Opera Android
36
|
Safari iOS 9 |
Samsung Internet Android
5.0
|
nodejs
6.0.0
|
构造函数
|
Chrome
49
|
Edge 13 | Firefox 45 | IE No |
Opera
36
|
Safari 9 |
WebView Android
49
|
Chrome Android
49
|
Firefox Android 45 |
Opera Android
36
|
Safari iOS 9 |
Samsung Internet Android
5.0
|
nodejs
6.0.0
|
extends
|
Chrome
49
|
Edge 13 | Firefox 45 | IE No |
Opera
36
|
Safari 9 |
WebView Android
49
|
Chrome Android
49
|
Firefox Android 45 |
Opera Android
36
|
Safari iOS 9 |
Samsung Internet Android
5.0
|
nodejs
6.0.0
|
| Private class fields | Chrome 74 | Edge 79 | Firefox No | IE No | Opera 62 | Safari 14 | WebView Android 74 | Chrome Android 74 | Firefox Android No | Opera Android 53 | Safari iOS 14 | Samsung Internet Android No | nodejs 12.0.0 |
| Public class fields | Chrome 72 | Edge 79 | Firefox 69 | IE No | Opera 60 | Safari 14 | WebView Android 72 | Chrome Android 72 | Firefox Android No | Opera Android 51 | Safari iOS 14 | Samsung Internet Android No | nodejs 12.0.0 |
static
|
Chrome
49
|
Edge 13 | Firefox 45 | IE No |
Opera
36
|
Safari 9 |
WebView Android
49
|
Chrome Android
49
|
Firefox Android 45 |
Opera Android
36
|
Safari iOS 9 |
Samsung Internet Android
5.0
|
nodejs
6.0.0
|
| Static class fields | Chrome 72 | Edge 79 | Firefox 75 | IE No | Opera 60 | Safari No | WebView Android 72 | Chrome Android 72 | Firefox Android No | Opera Android 51 | Safari iOS No | Samsung Internet Android No | nodejs 12.0.0 |
完整支持
不支持
见实现注意事项。
用户必须明确启用此特征。
A class can't be redefined. Attempting to do so produces a
SyntaxError
.
If you're experimenting with code in a web browser, such as the Firefox Web Console (
工具
>
Web Developer
>
Web 控制台
) and you 'Run' a definition of a class with the same name twice, you'll get a
SyntaxError: redeclaration of let
ClassName
;
. (See further discussion of this issue in
bug 1428672
.) Doing something similar in Chrome Developer Tools gives you a message like
Uncaught SyntaxError: Identifier '
ClassName
' has already been declared at <anonymous>:1:1
.
class
declaration
class
expression
super