❗Class
JavaScript 中的 class 是建立在 prototype 之上的,但它也有一些 class 特有的 syntax 和 semantics。
class 实际上是一种特殊的 function,它也有两种定义方式:
class declaration 类声明
但是,它不会被提升,也有 temporal dead zone(临时死区)限制,同
let
,const
class expression 类表达式
// Declaration
class Rectangle {
constructor(height, width) {
this.height = height
this.width = width
}
}
// Expression: the class is anonymous but assigned to a variable
const Rectangle = class {
constructor(height, width) {
this.height = height
this.width = width
}
};
// Expression: the class has its own name
const Rectangle = class Rectangle2 {
constructor(height, width) {
this.height = height
this.width = width
}
}
class 的代码体默认运行在 strict mode。
class 元素可以通过以下三个方面来表征:
getter setter method
field
instance static
public private
constructor()
constructor()
constructor()
用来 create 和 initialize 一个对象。在一个 class 中,只能有一个 constructor()
。
有两种字段:instance properties 和 class fields。
如果 instance properties 的 values 不依赖 constructor 的 arguments,则可以用 class fields。class fields 类似于 object properties 而不是 variables,所以声明时不需要使用 const
等关键字。如果声明时没有 default value,则默认是 undefined
。
class Rectangle {
// class fields
height = 0
width;
constructor(height, width) {
// instance properties
this.height = height
this.width = width
}
}
class Rectangle {
// private fields
#height = 0
#width
constructor(height, width) {
this.#height = height
this.#width = width
}
}
说明:private 特性有一个限制,那就是在同一个 class 中声明的所有 property names 必须唯一。而 public properties 则没有这个限制,当有多个 public property names 时,最后一个会 overwrites 其它的。
static initialization blocks
methods
可以是:
plain function
async function
generator function
async generator function
继承 inheritance
Last updated