圣杯模式
//简易版
function extend(Target,Origin){
function F(){}
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin;
}
//YUI库中的写法
var extend = (function(){
function F(){}
return function(Target,Origin){
F.prototype = Origin.prototype;
target.prototype = new F();
target.prototype.constructor = Target;
target.prototype.uber = Origin
}
})()
借用原型链实现继承
基本思想:利用原型让一个引用类型继承另一个引用类型的属性和方法,实现的本质是重写原型对象,代之以一个新类型的实例。
function SuperType(){
this.property = true
}
SuperType.prototype.getSuperValue = function(){
return this.property;
}
function SubType(){
this.subProperty = false;
}
//继承SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function(){
return this.subProperty;
}
var instance = new SubType();
instance.getSuperValue()//true
instance.getSubValue()//false
缺点:
- 包含引用类型值的原型属性会被所有实例共享。这样,一个实例修改了原型对象中引用类型值的原型属性,会在另外一个实例对象上也体现出来这种修改。
function SuperType(){
this.color =['red','green','blue']
}
function SubType(){}
SubType.prototype = new SuperType();
var instance1 = new SubType();
instance1.color.push('yellow');
var instance2 = new SubType();
instance2.color;//['red','green','blue','yellow']
- 在创建子类的实例时,无法向超类的构造函数中传递参数。
借用构造函数
思想:在子类构造函数的内部调用超类构造函数
function SuperType(name,age){
this.name = name;
this.age = age;
}
function SubType(name,age,gender){
SuperType.call(this,name,age);//就是这一步继承了superType。
this.gender = gender;
}
组合继承
function SuperType (name){
this.name = name;
}
SuperType.prototype.sayName =function(){
console.log(this.name);
}
function SubType (name,age){
SuperType.call(this,name);
this.age = age;
}
SubType.prototype = Object.create(SuperType.prototype);;
SubType.prototype.constructor = SubType;