日期:2014-05-16  浏览次数:20375 次

javascript多重继承小例子(zInherit工具)
function ClassX(){

	this.messageX = "This is the X message. ";
	
	if(typeof ClassX._initialized == "undefined"){
	
		ClassX.prototype.sayMessageX = function(){
		
			alert(this.messageX);
		};
		
		ClassX._initialized = true;
	}
}

function ClassY(){

	this.messageY = "This is the Y message. ";
	
	if(typeof ClassY._initialized == "undefined"){
	
		ClassY.prototype.sayMessageY = function(){
		
			alert(this.messageY);
		};
		
		ClassY._initialized = true;
	}
}

function ClassZ(){

	ClassX.apply(this);
	ClassY.apply(this);
	this.messageZ = "This is the Z message. ";
	
	if(typeof ClassZ._initialized == "undefined"){
	
		// 使用zinherit工具包中的inheritFrom方法,实现多重继承,inferitFrom只会修改prototype的状态,而不会重新赋值
		ClassZ.prototype.inheritFrom(ClassX);
		ClassZ.prototype.inheritFrom(ClassY);
		
		ClassZ.prototype.sayMessageZ = function(){
		
			alert(this.messageZ);
		};
		
		ClassZ._initialized = true;	
	}
}

function myload(){
	alert("cc");
	var objZ = new ClassZ();
	objZ.sayMessageX();
	objZ.sayMessageY();
	objZ.sayMessageZ();
}



zinherit简单的实现了多重继承,但使用inheritFrom后,objZ instanceof ClassY是无效的代码,因为这种方法根本不使用原型链,当然zinherit提供instanceOf方法来解决这个问题
objZ.instanceOf(ClassY);                  //  return true


但更加复杂的继承操作,zinherit将无法完成,比如:父类的调用,方法重载等,但很明显,zinherit的使用很方便,也很简单