ECMAScript只支持实现继承,而且其实现继承主要是依靠原型链来实现的
1.原型链
基本思想是利用原型让每一个函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型的内部指针.
function SuperType(){
this.property = true
};
SuperType.prototype.getSuperTypeValue = function() {
return this.property;
}
function SubType () {
this.Subproperty = false;
}
SubType.propotype = new SuperType();
SubType.propotype.getSuperTypeValue =function (){
return this.subproperty;
}
var instance = new SubType();
alert(instance.getSuperValue()); //true
2.借用构造函数
在子类型构造函数的内部调用超类型构造函数.使用call()和apply()的方法在先创建的对象上执行构造函数
function SuperType(){
this,color = ['red','blue','yellow'];
};
function SubType(){
SuperType.call(this); //继承了SuperType
}
var instance = new SuperType();
alert(instance.color) //'red','blue','yellow'
3.组合继承
有时候也叫伪经典继承.原型链和借用构造函数结合继承的一种.发挥二者之长的一种.
function SuperType(name){
this.name = name;
this,color = ['red','blue','yellow'];
};
SuperType.propotype.sayName = function(){
alert(this.name);
}
function SubType(){
SuperType.call(this); //继承了SuperType
}
SubType.propotype = new SuperTYpe();
SubType.propotype.construtor =SubType;
var instance = new SuperType(ls);
alert(instance.color) //'red','blue','yellow'
instance.sayName(); //'ls'