ES5寄生组合式继承

1,043 阅读1分钟
function Parent(name) {
  this.name = name
}

Parent.sayHello = function (){
  console.log('hello')
}

Parent.prototype.sayName = function() {
  console.log('my name is ' + this.name)
  return this.name
}

function Child(name, age) {
  Parent.call(this, name)
  this.age = age
}

function _inherits(Child, Parent) {
  Child.prototype = Object.create(Parent.prototype)
  Child.prototype.constructor = Child
  Child.__proto__ = Parent
}
_inherits(Child, Parent)

Child.prototype.sayAge = function () {
  console.log('my age is ' + this.age)
  return this.age
}

var parent = new Parent('Parent')
var child = new Child('Child', 18)
console.log(parent)
Parent.sayHello()
parent.sayName()
console.log(child)
Child.sayHello()
child.sayAge()
child.sayName()

总结三点:

1.子类构造函数的__proto__指向父类构造器,继承父类的静态方法

2.子类构造函数的prototype指向父类构造器的prototype,继承父类的方法

3.子类构造器里调用父类构造器,继承父类的属性