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中。相关文章推荐
- extjs 初始化函数 中的 this.callParent(arguments);类似于继承么?就是继承父类的对应的初始化函数
- javascript使用call方式实现对象继承
- JavaScript使用Call和Apply方法实现继承
- 利用javascript中的call实现继承
- JavaScript面向对象的方法实现继承:call方法
- 【Javascript】call方法实现JS中类的继承
- javascript _call3_实现继承
- javaScript面向对象的方法实现继承:call方法
- JavaScript中的call()和apply()方法,借此实现继承
- Ajax - JavaScript之实现私有属性、像C++和Java一样支持基于类的继承方法之例子
- javascript除call函数外实现继承的方式之一
- javascript 中的继承实现, call,apply,prototype,构造函数
- 利用javascript中的call实现继承
- javascript继承--call()和apply实现继承
- 理解call,this指针(用call实现继承),prototype模式实现继承的易错点
- JavaScript实现继承机制(2)——调用call()与apply()方法
- 基于JavaScript实现继承机制之调用call()与apply()的方法详解
- 【javascript】call或apply实现继承(多继承)
- 函数内部属性 arguments、this 以及非继承而来的方法 call()和 apply()
- 利用javascript中的call实现继承