2007-11-26
javascript中基于类的继承
关键字: javascript中基于类的继承xml 代码
- 在两个对象之间创建一个继承关系可以用函数来实现,函数如下:
- function creatInheritance(parent,child){
- var property;
- for(property in parent){
- if(!child[property]){
- child[property]=parent[property];
- }
- }
- }
- 这个函数迭代处理父对象的所有成员(属性和函数),如果某个成员在子对象中不存在,则复制到子对象。
- 使用creatInheritance函数的例子
- var child=new Child();
- creatInheritance(new Parent(),child);
- 父对象中有而子对象中没有的所有属性和方法将复制到子对象。
评论
ajaxgo
2007-11-27
lz的方法会失去instanceof(子类的实例instanceof 父类,变为false)
Prototype1.5曾用简单的extend原型方法做继承。但这样不好。目前比较常用的方法是:
[code]
Child.prototype=new Pranet(); //保留prototype链
_extend(Child.prototype,{ //子类的属性方法
.....
});
Child.prototype.constructor=Child; //修正constructor
[/code]
ps:为什么我现在在javaeye编辑帖子格式都不对???
afcn0
2007-11-26
不是给每个对象都配备了方法,而是每个对象都原形继承了inherit方法
dikar
2007-11-26
这样也好,给每个对象都配备了继承方法
afcn0
2007-11-26
不如改造下
这样更好点。
Object.prototype.inherit=function(object){
for(var property in object){
if(!this[property]){
this[property]=object[property];
}
}
};
child.inherit(new Parent());
这样更好点。
发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则







评论排行榜