ZhengXingchi / ZhengXingchi.github.io

Apache License 2.0
0 stars 0 forks source link

es5实现继承 #59

Open ZhengXingchi opened 4 years ago

ZhengXingchi commented 4 years ago

组合继承

  function Parent(name) {
      this.name = name
      this.colors = ['red', 'blue', 'green']
    }
    Parent.prototype.getName = function () {
      console.log(this.name)
    }
    function Child(name, age) {
      Parent.call(Child, name)
      this.age = age
    }
    Child.prototype = new Parent()
ZhengXingchi commented 4 years ago

寄生组合继承

    function Parent(name) {
      this.name = name
      this.colors = ['red', 'blue', 'green']
    }
    Parent.prototype.getName = function () {
      console.log(this.name)
    }
    function Child(name, age) {
      Parent.call(Child, name)
      this.age = age
    }
    function createObject(obj) {
      function F() { }
      F.prototype = obj
      return new F()

    }
// 不直接child.prototype=parent.prototype呢?
// 原因 : 当我们想给 Child 的prototype里面添加共享属性或者方法时,如果其 prototype 指向的是 Parent 的 prototype,那么在 Child 的 prototype 里添加的属性和方法也会反映在 Parent 的 prototype 里面,
// 这明显是不合理的,这样做的后果是当我们只想使用 Parent 时,也能看见 Child 往里面扔的方法和属性。
// 所以需要每个构造函数都需要持有自己专用的prototype对象
    let prototype = createObject(Parent.prototype)
    prototype.constructor = Child
    Child.prototype = prorotype
ZhengXingchi commented 4 years ago

参考文献

JS原型链与继承别再被问倒了