1.原型链
//很少单独使用
复制代码 代码如下:
view code
//定义 superclass类,有一个属性property和一个方法getsupervalue
function superclass() {
this.property = true;
}
superclass.prototype.getsupervalue = function() {
return this.property;
}
//定义subclass类,有一个属性subproperty和后来添加的一个方法getsubvalue
function subclass() {
this.subproperty = false;
}
//subclass类继承superclass类
subclass.prototype = new superclass();
//subclass类添加一个方法getsubvalue
subclass.prototype.getsubvalue = function() {
return this.subproperty;
}
//创建subclass类的实例
var instance = new subclass();
alert(instance.getsupervalue());
2. 确定原型与实例的关系
第一种方式用 instanceof 操作符,用来测试实例和原型链中出现过的构造函数
复制代码 代码如下:
alert(instance instanceof object); //true ,instance是object的实例吗?
alert(instance instanceof superclass); //true ,instance是superclass的实例吗?
alert(instance instanceof subclass); //true,instance是subclass的实例吗?
第二种方式用 isprototypeof()方法,测试原型链中出现的原型
复制代码 代码如下:
alert(object.prototype.isprototypeof(instance)); //true
alert(superclass.prototype.isprototypeof(instance)); //true
alert(subclass.prototype.isprototypeof(instance)); //true
3. 用原型链继承定义方法时的注意点
定义方法是的顺序:
复制代码 代码如下:
view code
function superclass() {
this.property = true;
}
superclass.prototype.getsupervalue = function() {
return this.property;
}
function subclass() {
this.subproperty = false;
}
//subclass继承superclass
subclass.prototype = new superclass(); //这个要先写,新添加的方法和重写超类的方法要写在后面,否则重写的超类方法将永远无法调用
//添加新方法
subclass.prototype.getsubvalue = function() {
return this.subproperty;
}
//重写超类的方法
subclass.prototype.getsupervalue = function() {
return false;
}
var instance = new subclass();
alert(instance.getsupervalue()); //fales,这里subclass的实例调用了subclass的getsupervalue()方法,而屏蔽了superclass的getsupervalue()方法,
//使用superclass的方法会调用superclass的getsupervalue()方法
原型链继承的缺点:1)共享超类中的属性,2)在创建子类时不能向超类的构造函数传递参数。所有很少单独使用原型链
4.借用构造函数
//很少单独使用
优点:可以向超类传递参数 。缺点:函数无法复用,所有类都要使用构造函数模式
复制代码 代码如下:
view code
function superclass(name) {
this.name = name;
}
function subclass(){
superclass.call(this,ruiliang); //继承了superclass,同时向superclass传递了参数
this.age = 29; //实例属性
}
var instance = new subclass();
alert(instance.name); //ruiliang
alert(instance.age); //29
6.组合继承
//最常用的继承模式
复制代码 代码如下:
view code
//创建superclass
function superclass(name) {
this.name = name;
this.colors = [red,blue,green];
}
superclass.prototype.sayname = function() {
alert(this.name);
}
////创建subclass
function subclass(name,age) {
superclass.call(this,name); //继承属性
this.age = age; //自己的属性
}
subclass.prototype = new superclass(); //继承方法
subclass.prototype.sayage = function() { //subclass添加新方法
alert(this.age);
};
//使用
var instance1 = new subclass(ruiliang,30);
instance1.colors.push(black);
alert(instance1.colors); //red,blue,green,black
instance1.sayname(); //ruiliang
instance1.sayage(); //30
var instance2 = new subclass(xuzunan,26);
alert(instance2.colors); //red,blue,green
instance2.sayname(); //ruiliang
instance2.sayage(); //30
7.其它继承模式
原型式继承、寄生式继承、寄生组合式继承