ES3/5 中的类(构造函数)的继承

146 阅读1分钟

1. 直接将父类 protoype 赋值给子类

Child.prototype = Father.prototype

缺点:会导致父类拥有子类方法

2. 将父类实例对象赋值给子类

Child.prototype = new Father()

// 解决子类 proto 中 constructor 为父类
Child.prototype.constructor = Child

缺点:

  • 会导致子类 poto 中有多余并且不可用的属性
  • 子类 proto 中 constructor 为父类 - (可解决)

3. 利用 Object.create() 方法 - 比较玩完美的继承方法

Child.prototype = Object.create(Father.prototype)

// 解决子类 proto 中 constructor 为父类
Child.prototype.constructor = Child

缺点:子类 proto 中 constructor 为父类 - (可解决)