您的位置:首页 > Web前端 > JavaScript

Javascript:继续实现继承,支持:this.callParent(arguments)

2013-05-02 06:35 357 查看

背景

上篇文章中,我简单的介绍了如何实现单继承。只是在子类中调用父类方法的方式让人感觉不是很爽:

var Animal = function () {
Animal.super().constructor.apply(this, arguments);
};


今天这篇文章的目的就是简化这种调用方式,期望的调用方式如下:

var Animal = function () {
this.callParent(arguments);
};


如何实现callParent呢?

只要做到如下几点,实现callParent就不是问题了,要求如下:

callParent必须知道哪个方法调用的它。

callParent必须知道调用它的那个方法的名字。

callParent必须知道调用它的那个方法的拥有者(prototype)。

callParent必须知道调用它的那个方法的拥有者的父类。

思路有了,实现就不是问题了

因为默认情况Javascript只支持1,而2、3和4都要在框架层面做出约束,框架要做的就是:一、为类型和方法增加相应的元数据;二、类型的方法定义必须使用Class.defineMethod方法进行定义。

代码示例

Function.prototype.defineMethod = function (methodName, methodBody) {
this.prototype[methodName] = methodBody;
methodBody.$name = methodName;
this.$owner = this;
};

Function.prototype.extend = function (baseType) {
var tempType = function () { };
tempType.prototype = baseType.prototype;

this.prototype = new tempType();
this.prototype.constructor = this;
this.prototype.callParent = function () {
var method = arguments.callee.caller;

return method.$owner.$baseType.prototype[method.$name].apply(this, arguments);
};

this.$baseType = baseType;
this.defineMethod('constructor', this.prototype.constructor);
this.super = function () {
return baseType.prototype;
};
};

var Base = function (name) {
console.log('Base');
this.name = name;
};

var Animal = function () {
this.callParent(arguments);
console.log('Animal');
};
Animal.extend(Base);

var Dog = function () {
this.callParent(arguments);
console.log('Dog');
};
Dog.extend(Animal);

var dog = new Dog('懒狗');


备注

整个实现有点借鉴ExtJS,当然ExtJS实现的就更完美了。我也有想法,希望把ExtJS的核心移植到NodeJS中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: