繼承

構(gòu)造函數(shù)的屬性繼承:借用構(gòu)造函數(shù)

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

function Student (name, age) {
  // 借用構(gòu)造函數(shù)繼承屬性成員
  Person.call(this, name, age)
}

var s1 = Student('張三', 18)
console.log(s1.type, s1.name, s1.age) // => human 張三 18

構(gòu)造函數(shù)的原型方法繼承:拷貝繼承

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

Person.prototype.sayName = function () {
  console.log('hello ' + this.name)
}

function Student (name, age) {
  Person.call(this, name, age)
}

// 原型對象拷貝繼承原型對象成員
for(var key in Person.prototype) {
  Student.prototype[key] = Person.prototype[key]
}

var s1 = Student('張三', 18)

s1.sayName() // => hello 張三

另一種繼承方式:原型繼承

function Person (name, age) {
  this.type = 'human'
  this.name = name
  this.age = age
}

Person.prototype.sayName = function () {
  console.log('hello ' + this.name)
}

function Student (name, age) {
  Person.call(this, name, age)
}

// 利用原型的特性實現(xiàn)繼承
Student.prototype = new Person()

var s1 = Student('張三', 18)

console.log(s1.type) // => human

s1.sayName() // => hello 張三

?