继承:
原型链:
function supertype()
{this.color=["blue","red","yellow"];
}
function subtype(){}
subtype.prototype=new supertype();
var instance=new subtype();
instance.color
"blue"
subtype继承了supertype,instane是subtype的实例,instance指向subtype的原型,subtype的原型又指向supertype的原型。
instance instanceof Object
true
instance instanceof supertype
true
instance instanceof subtype
true
isPrototypeOf()方法也可以判断是不是该原型链派生出来的的实例的原型
Object.prototype.isPrototypeOf(instance)
true
supertype.prototype.isPrototypeOf(instance)
true
subtype.prototype.isPrototypeOf(instance)
true
给原型添加方法的代码一定要放在替换原型的语句之后
原型链实现继承时,不能使用对象字面量(简单的方法)创建原型方法,因为这样就会重写原型链。
构造函数:
function supertype(){this.color=["blue","red","yellow"];}
function subtype(){supertype.call(this);}
var instance=new subtype();
instance.color
["blue", "red", "yellow"]
构造函数方法可以在子类型构造函数中向超类型构造函数传递参数。
f
unction supertype(name){this.name=name;}
function subtype(){supertype.call(this,"nick");this.age=12;}
var instance=new subtype();
instance.name;
"nick"
instance.age;
12
组合继承:
结合原型链和构造函数方法
function supertype(name){this.name=name;this.color=["yellow","blue","red"];}
supertype.prototype.sayname=function(){alert(this.name);}
function subtype(name,age){supertype.call(this,name);this.age=12;}
subtype.prototype=new subtype();
subtype.prototype.sayage=function(){alert(this.age);}
function (){alert(this.age);}
var instance=new subtype("lucy",12)
instance.name
"lucy"
instance.age
12