传统形式(原型链继承)
Grand.prototype.lastName = 'hkp';
function Grand(){
}
var grand = new Grand();
Father.prototype = grand;
function Father(){
this.name = 'baba'
}
var father = new Father();
Son.prototype = father;
function Son(){
}
var son = new Son();
//既有lastName,也有name,过多的继承了没有的属性
借用构造函数
function Animal(name,age){
this.name = name;
this.age = age;
}
function Dog(name,age,grade){
Animal.call(this,name,age);
this.grade = grade;
}
var dog = new Dog('狗蛋',18,1);
//不能继承构造函数的原型
//每次构造函数都要多走一个函数
共享原型
Father.prototype.lastName = 'hkp';
function Father(){
}
function Son(){
}
Son.prototype = Father.prototype;
Son.prototype.name = 'ji';
var son = new Son();
var father = new Father();
//father对象也具有了name属性
//不能随便改动自己的原型
圣杯模式
相传如果能找到圣杯而喝下其盛过的水就将返老还童、死而复生并且获得永生
var inherit = (function(){
function F(){};
return function(Target,Origin){
F.prototype = Origin.prototype;
Target.prototype = new F();//通过函数F实现原型链继承
Target.prototype.constructor = Target;//指向构造该对象的构造函数
Target.prototype.order = Origin.prototype;//指向真正继承的父级
}
})()
Father.prototype.lastName = 'hkp';
function Father(){
}
function Son(){
}
inherit(Son,Father);
var son = new Son();
var father = new Father();