日期:2014-05-16 浏览次数:20499 次
function SuperType(name){
	this.name = name;
	this.colors = ['red','green','blue'];
};
SuperType.prototype.getName = function(){
	return this.name;
}
function SubType(name,age){
	//继承所有属性
	SuperType.call(this,name);
	this.age = age;
}
//继承父类的方法
SubType.prototype = new SuperType();
//修复constructor的指向
SubType.prototype.constructor = SubType;
SubType.prototype.getAge = function(){
	return this.age;
}
var s1 = new SubType('Tom',10);
alert(s1.getName());
alert(s1.getAge());
alert(s1.getColor());
s1.color.push('black');
var s2 = new SubType('Jerry',8);
alert(s2.color);
//函数prototype上的属性都是共有
alert(s1.getAge === s2.getAge);//true
alert(s1 instanceof SubType);//true
alert(s1 instanceof SuperType)//true
alert(s1.constructor == SubType)//ture
alert(s1.constructor == SuperType);//false
alert(s1.getName === s2.getName);//true

function object(o){
	function F(){}
	F.prototype = o;
	return new F();
}
//使用示例
//引用类型的属性将被共享
var person = {
	name: 'Tomy',
	friends:['1','3','4']
}
var p2 = object(person);
p2.name = 'Jack';
p2.friends.push([5,6]);
alert(p2.friends);//1,3,4,5,6
var p1 = object(person);
alert(p1.name)//Tomy
alert(p1.friends);//1,3,4,5,6

function inheritPrototype(subType,superType){
	var prototype = object(superType.prototype);
	prototype.constructror = subType;
	subType.prototype = prototype;
	
}
举例:
function SuperType(name){
	this.name = name;
	this.colors = ['red','green','blue'];
};
SuperType.prototype.getName = function(){
	return this.name;
}
function SubType(name,age){
	//继承所有属性
	SuperType.call(this,name);
	this.age = age;
}
//继承父类的方法
inheritPrototype(subType,superType);
//子类共有方法
SubType.prototype.getAge = function(){
	return this.age;
}