通过Child.prototype.__proto__ = Father.prototype进行原型链继承有何弊端?

function Father(money, house, car, huabei) {
    this.money = money
    this.house = house
      this.car = car
      this.huabei = huabei
}
``

Father.prototype.sayHi = function () {
    console.log(this)
}
function Child(money, house, car, huabei, gf) {
      // 属性继承
    Father.apply(this, [ money, house, car, huabei ])
      this.gf = gf
}

方法一:

// 这种方式缺点:会污染父构造函数的prototype属性
 Child.prototype = Father.prototype
 Child.prototype.kiss = function () {
    code....}

方法二:

// 这种方式缺点:语义不明,因为Father很有可能有参数,而此时传参不语义,我们的目的只想要一个原型链的继承,而没有实际的对象实例
Child.prototype = new Father()

方法三:

Child.prototype.__proto__ = Father.prototype

--------最佳的实现方式

// 前置知识:var obj2 = Object.create(obj1)
// 创建一个对象 obj2,让 obj2.__proto__ 指向 obj1
// 缺点:Object.create 兼容有点小问题,不支持的时候需要自己实现
Child.prototype = Object.create(Father.prototype)
Child.prototype.constructor = Child

为什么Child.prototype = Object.create(Father.prototype)
Child.prototype.constructor = Child的继承方式是相对最优的,而非Child.prototype.__proto__ = Father.prototype

阅读 1.3k
1 个回答

Child.prototype.__proto__ = Father.prototype
我理解你是想说实例上的原型等价于要继承的原型

  1. 无法继承原型上的传参
  2. 所有新实例上的属性都共用

Object.create()

  1. 原理是用函数包装成对象,方便函数任意添加属性和方法
  2. 同样所有新实例都会继承原型上的属性
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题