Chinaunix首页 | 论坛 | 博客
  • 博客访问: 203155
  • 博文数量: 73
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 750
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-13 18:32
文章分类

全部博文(73)

文章存档

2009年(1)

2008年(72)

我的朋友

分类: 系统运维

2008-04-06 11:35:07

  1,使用对象冒充的方式实现继承
 
function ClassA(sColor){
    this.color=sColor;
    this.sayColor=function(){
        alert(this.color);
    }
}
function ClassB(sColor,name){
    this.newMethod=ClassA;
    this.newMethod(sColor);
    //删除新方法,所有的新属性及其方法在之后定义
    delete this.newMethod;
    this.name=name;
    //另外这里方法的定义如果采用从prototype
    //继承的方式效率更佳
    this.sayName=function(){
        alert(this.name);
    }
}
var b=new ClassB("red","biao");
b.sayColor();
b.sayName();
#使用对象冒充,ClassB并没有真正继承了CLassA.只是添加了CLassA中的方#法而已。
#可以使用alert(b instanceof ClassA)进行检验。
#使用对象冒充方式的继承具有如下的缺点。在实现多重继承时比如ClassZ从ClassX,ClassY继承,
  this.newMethod=ClassX;this.newMethod(..);
  delete this.newMethod;
  this.newMethod=ClassY;this.newMethod(..);
  delete this.newMethod;
  若ClassX,ClassY中存在方法重名的现象则只会使用CLassY中的方法,因为它是在ClassX之后被继承的。

   
  2,原型链方式
   
function ClassB(){}
ClassB.prototype=new ClassA("yellow");
ClassB.prototype.sayName=function(){
    alert(this.name);
}
var b=new ClassB();
b.color="red"
b.name="biao"
b.sayColor();
b.sayName();
alert(b instanceof ClassA);//true
alert(b instanceof ClassB);//true
#输出是一样的。

  3,混合方式
 
function ClassA(sColor){
    this.color=sColor;
}
ClassA.prototype.sayColor=function(){
    alert(this.color);
}
function ClassB(sColor,name){
    ClassA.call(this,sColor);
    this.name=name;
}
ClassB.prototype=new ClassA();
ClassB.prototype.sayName=function(){
    alert(this.name);
}
var b=new ClassB("red","biao");
b.sayColor();
b.sayName();

阅读(857) | 评论(0) | 转发(0) |
0

上一篇:JavaScript Complete(四) 对象

下一篇:系列 一

给主人留下些什么吧!~~