Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}

toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}

等价于

function Pointer(x, y){
this.x = x
this.y = y
}

Pointer.prototype.toString = function (){
return '(' + this.x + ', ' + this.y + ')';
}
1
2
3
4
Object.assign(Point.prototype, {
toString(){},
toValue(){}
})

一次向类添加多个方法

特性

类的所有方法都定义在类的prototype属性
类的内部所有定义的方法,都是不可枚举的
实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)
类的所有实例共享一个原型对象

使用 Object.getPrototypeOf 方法来获取实例对象的原型,然后再来为原型添加方法/属性

取值函数(getter)和存值函数(setter)

存值函数和取值函数是设置在属性的 Descriptor 对象上

Class 表达式

1
2
3
4
5
const MyClass = class Me {
getClassName() {
return Me.name;
}
}

这个类的名字是Me,但是Me只在 Class 的内部可用,指代当前类。在 Class 外部,这个类只能用MyClass引用

注意点

  • 类和模块的内部,默认就是严格模式
  • 类不存在变量提升(hoist)
  • class 内部是严格模式,所以 this 实际指向的是 undefined
  • static 关键字,表示该方法不会被实例继承,而是直接通过类来调用

参考文档