2007-11-26

javascript中基于类的继承

关键字: javascript中基于类的继承
xml 代码
  1. 在两个对象之间创建一个继承关系可以用函数来实现,函数如下:   
  2. function creatInheritance(parent,child){   
  3. var property;   
  4. for(property in parent){   
  5.   if(!child[property]){   
  6.      child[property]=parent[property];   
  7.        }   
  8.      }   
  9. }   
  10. 这个函数迭代处理父对象的所有成员(属性和函数),如果某个成员在子对象中不存在,则复制到子对象。   
  11. 使用creatInheritance函数的例子   
  12. var child=new Child();   
  13. creatInheritance(new Parent(),child);   
  14. 父对象中有而子对象中没有的所有属性和方法将复制到子对象。   
评论
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());

这样更好点。
发表评论

提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则

您还没有登录,请登录后发表评论

dikar
搜索本博客
存档
最新评论