总结出JavaScript有以下几种继承继的方法:
1.对象冒充方法,可以多承继;
如:
2.原型链法;
如:
3.拷贝复制法
如:
4.call()方法,可以多承继;
如:
5.apply()方法,可以多承继;
如:
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());
本文总结了JavaScript中五种实现继承的方法,包括对象冒充、原型链、拷贝复制、call及apply方法,并提供了每种方法的具体实例。
7318

被折叠的 条评论
为什么被折叠?



