先定义一个对象classA,我们要实现一个新对象,继承classA
[code]
function classA(sColor){
this.color=sColor;
this.sayColor=function(){
alert(this.color);
}
}
[/code]
1. 用call方法实现继承
[code]
function classC(sColor,sName){
classA.call(this,sColor);
this.name=sName;
this.sayName=function(){
alert(this.name);
}
}
var obj1=new classC("red","jack");
obj1.sayColor();
obj1.sayName();
[/code]
2.用apply方法实现继承,
这种方法的本质和call方法是一致的,不同的是APPLY的第个参数是数组(包含了要传递的所有参数)
[code]
function classD(sColor,sName){
classA.apply(this,new Array(sColor));
this.name=sName;
this.sayName=function(){
alert(this.name);
}
}
var obj2=new classD("blue","sherry");
obj2.sayColor();
obj2.sayName();
[/code]
3. 原型方法, 请参考我的前篇文章
[url="http://ssh-2009-126-com.iteye.com/blog/394978"]JAVASCRIPT定义对象的四种方式[/url]
4. 构造函数,原型混合方法
[code]
function classA(sName){
this.name=sName;
}
classA.prototype.sayName=function(){
alert(this.name);
}
function classB(sName,sHeight){
classA.call(this,sName)
this.height=sHeight;
}
classB.prototype=new classA();
classB.prototype.sayHeight=function(){
alert(this.height);
}
var obj3=new classA("jack");
obj3.sayName();
var obj4=new classB("shrry",27);
obj4.sayName();
obj4.sayHeight();
[/code]
5. 使用类似于Prototype extend 方法
[code]
function extend(childclass,superclass){
var func=function(){};
func.prototype=superclass.prototype;
childclass.prototype=new func();
childclass.prototype.constructor=childclass;
}
[/code]