继承

原型链方法

继承了过多没用的属性

通过使用new关键字来实现继承父元素属性和方法,再通过prototype属性来改变函数原型,从而实现一条完整的原型链,从而实现子函数可以继承父函数的属性和方法

function Father() {
    this.name = 'hhh';
}
var father = new Father();
Son.prototype = father;
function Son() {
}
var son = new Son();//son下继承了father的name

借用构造函数

不能继承构造函数的原型

 // 1. 父构造函数
 function Father(uname, age) {
   // this 指向父构造函数的对象实例
   this.uname = uname;
   this.age = age;
 }
  // 2 .子构造函数 
function Son(uname, age, score) {
  // this 指向子构造函数的对象实例
 // 3.使用call方式实现子继承父的属性
  Father.call(this, uname, age);
  this.score = score;
}
var son = new Son('lin', 19, 100);
console.log(son);

共享原型

Son.prototype = Father.prototype,不能改动自己的原型

Father.prototype.lastName = 'lin';
function Father() {
    this.name = 'hhh';
}
function Son() {
}
Son.prototype = Father.prototype;//son和father共用原型
var father = new Father();
var son = new Son();

圣杯模式

在共享原型的基础上加多一个构造函数F做中间层,让F和Father共有原型,也就是把Father的原型赋值给F一份,在F和son之间操作,这样就可以隔开son和father但又不影响继承

function inherit(Target,Origin) {
    function F() {}
    F.prototype = Origin.prototype;//把父元素的原型给F
    Target.prototype = new F();//通过new的方法把F的原型返回给目标
}
Father.prototype.lastName = 'lin';
function Father() {}
function Son() {}
inherit(Son.Father);
var son = new Son();
var father = new Father();