# 继承

# ES5中的继承

function Parent(name) {
  this.name = name
  this.run = function() {
    console.log(this.name + ' is running')
  }
}
Parent.prototype.age = 23
Parent.prototype.work = function() {
  console.log(this.name + ' is working')
}
1
2
3
4
5
6
7
8
9
10

# 原型链继承

function Child(name) {
  this.name = name
}
Child.prototype = new Parent()
const c = new Child('child1')
c.run() // child1 is running
console.log(c.age) // 23
console.log(c.name) // child1
c.work() // child1 is working
1
2
3
4
5
6
7
8
9

# 构造函数继承

function Child(name) {
  Parent.call(this, name)
}
const c = new Child('child3')
c.run() // child3 is running
console.log(c.age) // undefined
console.log(c.name) // child3
c.work() // 报错
1
2
3
4
5
6
7
8
上次更新时间: 9/12/2021, 10:30:35 PM