1.传统继承 --》原型链
缺点:过多的继承链没用的属性
Grand.prototype.lastName = '张三';
function Grand(){
}
var grand = new Geand();
Father.prototype = grand;
function Father(){
this.name = '王五';
}
var father = new Father();
Son.prototype = father;
function Son(){
this.hobbit = '赵六';
}
var son = new Son()
2.借用构造函数
缺点:
1.不能继承借用构造函数的原型
2.每次构造函数都要多走一个函数 (每次执行了两个方法)
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();
3.共享原型
缺点:不能随便改动自己的原型
Father.prototype.lastName = '张三';
function Father(){
}
function Son(){
}
Son.prototype = Father.prototype;
var son = new Son();
var father = new Father();
4.圣杯模式
Father.prototype.lastName = '张三';
function Father(){
}
function Son(){
}
var inherit = (function(){
var F = function(){};
return function(Target,Origin){
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target; //Target的constructor方法归位
Target.prototype.uber = Origin.prototype;// 超类,真正继承的来源
}
}())
inherit(Son,Father)
var son = new Son();
var father = new Father();