JavaScript经典面试题---继承的几种方式

210 阅读1分钟

一: 原型链

Grand.prototype.lastName = "Niclo";
function Grand() {

}
var grand = new Grand();
Father.prototype = grand;
function Father() {
  this.name = 'hello'
}
var father = new Father();
Son.prototype = father
function Son() {

}
var son = new Son()
比如son只想继承lastName,但是Father里面的name也继承了,继承了很多没用的属性

缺点:

  • 过多的继承了没用的属性

二:借用构造函数

Person.prototype.sayHello = function() {
  console.log('say hello')
}
function Person(name,age,sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}
function Student(name,age,sex,grade) {
  Person.call(this,name,age,sex);
  this.grade = grade;
}
var student = new Student();

缺点:

  • 不能继承借用构造函数的原型
  • 每次构造函数都要多走一个函数

三: 共享原型

Father.prototype.lastName="shi";
function Father() {

}
var father = new Father();
Son.prototype = Father.prototype;
function Son() {

}
var son = new Son()

//把上面内容封装成函数
Father.prototype.lastName="shi";
function Father() {

}
function Son() {

}
function inherit(Target,Origin) {
  Target.prototype = Origin.prototype
}
inherit(Son,Father)
var son = new Son()
var father = new Father()
Son.prototype.sex = 'male'
son.sex //male
father.sex //male

发现Son原型里自定义sex后,影响father了

缺点:

  • 不能随便改动自己的属性

四: 圣杯模式

Father.prototype.lastName="shi";
function Father() {

}
function Son() {

}
function inherit(Target,Origin) {
  function F() {

  }
  F.prototype = Origin.prototype
  Target.prototype = new F()
}
inherit(Son,Father)
var son = new Son()
var father = new Father()
Son.prototype.sex = 'male'
son.sex //male
father.sex //undefined