1.传统形式
过多的继承了没用的属性
2.借用构造函数
不能继承借用构造函数的原型
每次构造函数都要多走一个函数
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name,age,sex,tel,grade){
// this.name = name;
// this.age = age;
// this.sex = sex;
Person.call(this,name,age,sex);//借用别人的函数实现自己的功能
// Person.apply(this,[name,age,sex]); 改变this指向,传参列表不同。call需要把实参按照形参的个数传进去 apply需要传一个arguments
this.tel = tel;
this.grade = grade;
}
3.共享原型
不能随便改动自己的原型
Father.prototype = {
lastName :'dd'
}
function Father(){
}
function Son(){
}
function inherit(Target,Origin){
Target.prototype = Origin.prototype;
}
inherit(Son,Father);
var son = new Son();
//如果给Son添加属性 Son.prototype.sex = “male”那么其父亲也将拥有这个属性
即 var father = new Fatner(); father.sex == “male” -- >true(解决:圣杯模式)
- 圣杯模式
function inherit(Target, Origin) {
function F(){}
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;//超类
}
YAHOO(YUI): var inherit = (function(){
function F(){}
return function(Taget,Orgin){
F.prototype = Orgin.prototype;
Taget.prototype = F.prototype;
Taget.prototype.constructor = Taget;
Taget.prototype.uber = Orgin.prototype;
}
}());