js 继承

寄生组合式继承

// 实现继承。调用一次父类的构造函数
function inheritPrototype (subType, superType) {
  // 根据父类原型创建一个新的原型对象
  /*
    // Object.create传递一个参数是相当于下面代码:
    function createObj (obj) {
      function F () {}
      F.prototype = obj
      return new F()
    }
   */
  let prototype = Object.create(superType.prototype)
  // 为原型对象创建指定子类的构造函数,防止构造函数丢失
  prototype.constructor = subType
  // 为子类指定原型对象
  subType.prototype = prototype
}

// 父类构造函数
function Father () {
  this.name = 'father'
  this.data = [1,2,3]
}
// 父类方法
Father.prototype.sayName = function () {
  console.log('name: ', this.name)
}

// 子类构造函数
function Child (age) {
  Father.call(this)
  this.age = age
}
// 继承父类
inheritPrototype(Child, Father)
// 子类方法。需要继承后才能定义子类的方法,否则子类方法会被继承里面的原型对象覆盖,造成子类方法丢失
Child.prototype.sayAge = function () {
  console.log('age: ', this.age)
}


let child = new Child(12)
console.log(child, child.data)
child.sayAge()
child.sayName()
child.data.push(4)
console.log(child.data)
console.log('>>>>>>>>')

let child1 = new Child(14)
console.log(child1, child1.data)
child1.sayAge()
child1.sayName()

/*
控制台输出:

    Child { name: 'father', data: [ 1, 2, 3 ], age: 12 } [ 1, 2, 3 ]
    age:  12
    name:  father
    [ 1, 2, 3, 4 ]
    >>>>>>>>
    Child { name: 'father', data: [ 1, 2, 3 ], age: 14 } [ 1, 2, 3 ]
    age:  14
    name:  father
 */

posted @ 2021-04-13 11:17  Lanomw  阅读(49)  评论(0编辑  收藏  举报