注意的几个点 :
- 在
class
中定义的方法, 均为原型方法
class F{
say(){}
}
F.prototype.hasOwnProperty('say') //true
class
中定义的属性, 均为实例属性, 而非在原型上, 并且构造函数中定义相同属性会覆盖class
中的定义
class W {
a = 1
constructor(){
this.a = 2
}
}
let w = new W()
w.hasOwnProperty('a') //true
w.a // 2
- 类本身指向构造函数
Object.getPrototypeOf(w).constructor === W
class
没有写构造函数, 会自动创建一个, 并返回this
- 与
es5
不同的是, 类中定义的方法是不可枚举的,es5
的prototype
写法可以
//class
class F {
say(){}
}
Object.keys(F.prototype) // []
// es5
function G() {}
G.prototype.say = function(){}
Object.keys(G.prototype) // ['say']
__proto__
并不是语言本身的特性,这是各大厂商具体实现时添加的私有属性,我们可以使用 Object.getPrototypeOfstatic
修饰的方法不会被实例继承, 静态方法, 只能被类调用, 可以与实例方法重名
class H {
static say(){
console.log(1)
}
say(){
console.log(2)
}
}
let h = new H()
h.say() // 2
H.say() // 1
- 使用
extends
继承时, 若子类显式地写了构造函数, 那么构造函数 中必须调用super()
, 子类未显式写构造函数则不用 class
中可以写get
,set
class K{
get a(){
return this.b
}
set a(val){
this.b = val
}
}