总结出JavaScript有以下几种继承继的方法:
1.对象冒充方法,可以多承继;
如:
A=function()
{
this.code="001";
this.name="whiteangell";
this.getCode=function()
{
return this.code;
}
this.getName=function()
{
return this.name
}
};
B = function()
{
this.newMethod=A;
this.newMethod();
this.age=20;
this.getAge=function()
{
return this.age;
}
};
var bb = new B();
alert(bb.getName());
2.原型链法;
如:
A=function()
{
this.code="001";
this.name="whiteangell";
this.getCode=function()
{
return this.code;
}
this.getName=function()
{
return this.name
}
};
B = function()
{
this.age=20;
this.getAge=function()
{
return this.age;
}
};
B.prototype=new A();
var bb = new B();
alert(bb.getName());
3.拷贝复制法
如:
Object.extend = function(destination,source)
{
for ( pro in source )
{
destination [pro] = source [pro];
}
return destination ;
};
A = function(){};
A.prototype =
{
code:"001",
name:"whiteangell",
getCode:function()
{
return this.code;
},
getName:function()
{
return this.name
}
};
B= function(){};
B.prototype= Object.extend({
age:20,
getAge:function()
{
return this.age;
}
},A.prototype);
var bb = new B();
alert(bb.getName());
4.call()方法,可以多承继;
如:
A=function()
{
this.code="001";
this.name="whiteangell";
this.getCode=function()
{
return this.code;
}
this.getName=function()
{
return this.name
}
};
B = function()
{
A.call(this);
this.age=20;
this.getAge=function()
{
return this.age;
}
};
var bb = new B();
alert(bb.getName());
5.apply()方法,可以多承继;
如:
A=function()
{
this.code="001";
this.name="whiteangell";
this.getCode=function()
{
return this.code;
}
this.getName=function()
{
return this.name
}
};
B = function()
{
A.apply(this);
this.age=20;
this.getAge=function()
{
return this.age;
}
};
var bb = new B();
alert(bb.getName());