JavaScript的继承

1.调用基类的构造函数

function classA(sColor)
		{
			this.color = sColor;
			this.sayColor = function()
			{
				alert(this.color);
			};
		}
		
		function classB(sColor,sName)
		{
			this.newMethod = classA;
			this.newMethod(sColor);
			delete this.newMethod;
			this.name = sName;
			this.sayName = function()
			{
				alert(this.name);
			};
		}
		
		/*var objA = new classA('red');
		var objB = new classB('blue','classb');
		objA.sayColor();
		objB.sayColor();
		objB.sayName();*/

2.使用apply,call函数

function classC(sColor)
		{
			this.color = sColor;
			this.sayColor = function()
			{
				alert(this.color);
			};
		}
		
		function classD(sColor,sName)
		{
			//classC.call(this,sColor);
			classC.apply(this,new Array(sColor));
			this.name = sName;
			this.sayName = function()
			{
				alert(this.name);
			};
		}
		
		/*var objC = new classC('redc');
		var objD = new classD('blued','classd');
		objC.sayColor();
		objD.sayColor();
		objD.sayName();*/

3.原型继承

function classE(sColor)
		{
			this.color = sColor;
		}
		classE.prototype.sayColor = function()
		{
			alert(this.color);
		};
		
		function classF(sColor,sName)
		{
			classE.call(this,sColor);
			this.name = sName;
		}
		classF.prototype = new classE();
		classF.prototype.sayName = function()
		{
			alert(this.name);
		};
		
		/*var objE = new classE('red2');
		var objF = new classF('blue2','classf');
		objE.sayColor();
		objF.sayColor();
		objF.sayName();
		if(objF instanceof classE) alert('objF instanceof classE');*/

相关推荐