西红柿爱番茄

Feed Rss

连缀语法的方式实现继承

12.17.2009, Javascript, by .

javascrpt里继承的方式很多种,有类式继承和原型继承(权威的解释:Prototypal Inheritance in JavaScript Classical Inheritance in JavaScript)。js没有像java那种只要通过一个extends关键字来声明继承的方式,它的实现方式是比较丑陋的,所以封装这个继承过程就显得尤为重要了。

下面我来说明一种链式封装继承的方式,这种方式需要扩展鼎鼎大名的method和inherits扩展方法。method是douglas crockford通过扩展Function类来方便声明方法从而出名。

[javascript]
//首先来实现method扩展方法:
Function.prototype.method=function(name,fn){
if(!this.prototype.name){ //验证是否已经存在该方法
this.prototype[name]=fn;
}
return this;
}

//接下来实现inherits扩展方法,它主要是用于封装继承:
Function.method("inherits",function(parent){
this.prototype=new parent;
this.prototype.constructor=this; //纠正子类constructor的指向错误
return this;
}
[/javascript]

上面的两个方法是实现所谓的连缀语法继承的基础,接下来看具体的实例就知道了:
[javascript]
//所谓的“父类”
var Person=function(n){
this.name=n;
}
Person.method("getName",function(){
return this.name;
});
//所谓的“子类”,下面的就是所谓的连缀方式了
var Student=function(n,g){
Person.call(this,n);
this.group=g;
}.inherites(Person).method("getGroup",function(){
return this.group;
});
[/javascript]
结语:还是那句话说的好:没事别扩展Javascript的内置类或者对象。这可能导致一些for…in循环产生怪异的事情。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>