当前位置:编程学习 > JS >>

JS的继承是从一个对象原型向另一个对象原型的简单拷贝

 
JavaScript支持面向对象,但是其实现方式是通过简单的从一个对象原型向另一个对象原型的拷贝的方式来实现的。 
实例如下:
 
[javascript] 
var BaseCls={};  
  
BaseCls.getName=function(){  
    return "base class";  
}  
  
  
var ChildCls = {};  
  
ChildCls.getName = BaseCls.getName;  
  
BaseCls.getName=function(){  
    return "base class changed";  
}  
  
alert(ChildCls.getName());  
  
alert(BaseCls.getName());  
 
var BaseCls={};
 
BaseCls.getName=function(){
return "base class";
}
 
 
var ChildCls = {};
 
ChildCls.getName = BaseCls.getName;
 
BaseCls.getName=function(){
return "base class changed";
}
 
alert(ChildCls.getName());
 
alert(BaseCls.getName());ChildCls.getName = BaseCls.getName;是将BaseCls的getName的定义复制给ChildCls的getName函数,之后对BaseCls的getName的改变不会影响到ChildCls的getName函数。
 
同样,用prototype继承也是相同的效果:
 
 
[javascript]
var BaseCls={};  
  
BaseCls.getName=function(){  
    return "base class";  
}  
  
function ChildCls(){  
      
}  
  
ChildCls.prototype.getName = BaseCls.getName;  
  
BaseCls.getName=function(){  
    return "base class changed";  
}  
  
alert(new ChildCls().getName());  
  
alert(BaseCls.getName());  
 
var BaseCls={};
 
BaseCls.getName=function(){
return "base class";
}
 
function ChildCls(){
 
}
 
ChildCls.prototype.getName = BaseCls.getName;
 
BaseCls.getName=function(){
return "base class changed";
}
 
alert(new ChildCls().getName());
 
alert(BaseCls.getName());
 
补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,