posts - 403, comments - 310, trackbacks - 0, articles - 7
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

JavaScript 学习 - Inheritance

Posted on 2007-05-05 18:57 ZelluX 阅读(278) 评论(0)  编辑  收藏 所属分类: Web
1. Javascript中的继承要自己模拟实现。一些常用方法:
a) Object masquerading
function ClassA(sColor) {
    
this.color = sColor;
    
this.sayColor = function () {
        alert(
this.color);
    }
;
}

function ClassB(sColor, sName) {
    
this.newMethod = ClassA;
    
this.newMethod(sColor);
    
delete this.newMethod;
    
this.name = sName;
    
this.sayName = function () {
        alert(
this.name);
    }
;
}
通过调用ClassA的生成方法,ClassB继承了ClassA的属性和方法,同时newMethod所占用的空间也被释放。

另外,Object masquerading还支持多重继承,方法类似。

b) 使用call()方法
感觉这个方法类似于Java反射机制中的invoke方法,第一个参数是个调用的对象主体,后面是被调用方法的参数。
function ClassB(sColor, sName) {
    ClassA.call(
this, sColor);
    
this.name = sName;
    
this.sayName = function () {
        alert(
this.name);
    }
;
}
ClassB通过调用ClassA的生成方法完成了初始化。

c) 使用apply()方法
和call()方法很相似,不同的是apply方法只有两个参数,一个是调用对象主体,一个是参数数组。
因此只要被上例的call语句改成ClassA.apply(this, new Array(sColor));即可

d) prototype链
function ClassA() {
}

ClassA.prototype.color 
= “red”;
ClassA.prototype.sayColor 
= function () {
    alert(
this.color);
}
;
function ClassB() {
}

ClassB.prototype 
= new ClassA();
注意被继承的类ClassA构造方法里没有任何参数。
ClassB新的属性要在prototype被赋值后再添加,否则就会被删除。
这种方法的好处在于,使用instanceof判断子类对象和父类的关系的结果是true,和面向对象的思想一致。

e) 混合
Object masquerading的缺点在于性能不好,而prototype链又只能用无参构造器。因此要把两者结合起来。
function ClassA(sColor) {
    
this.color = sColor;
}

ClassA.prototype.sayColor 
= function () {
    alert(
this.color);
}
;
function ClassB(sColor, sName) {
    ClassA.call(
this, sColor);
    
this.name = sName;
}

ClassB.prototype 
= new ClassA();
ClassB.prototype.sayName 
= function () {
    alert(
this.name);
}
;
要求ClassA在创建的时候也使用了prototype和constructor方法。

f) 动态创建的类的继承
function Triangle(iBase, iHeight) {
    Polygon.call(
this3);
    
this.base = iBase;
    
this.height = iHeight;
    
if (typeof Triangle._initialized ==     “undefined”) {
        Triangle.prototype.getArea 
= function () {
            
return 0.5 * this.base * this.height;
        }
;
        Triangle._initialized 
= true;
    }

}

Triangle.prototype 
= new Polygon();
注意prototype继承这一语句是在最后执行的,也不能被封装进构造器中。

2. zInherit库
简略的看了下,基本功能Prototype框架都提供。

3.xbObjects
同样是个库,略

只有注册用户登录后才能发表评论。


网站导航: