- // 根类object的定义
- function object() {
- /* object 基本类 */
- };
- object.prototype.isA = function(aType) {
- var self = this.type; // 调用isA()的当前类
- while (self) {
- if (self == aType) return true;
- self = self.aBase; // 检查基类是否相等
- }
- return false;
- };
- // object.prototype.base = function() { // 用于调用基类的构造函数
- // var Caller = object.prototype.base.caller; // 当前构造函数create()
- // Caller && Caller.Base && Caller.Base.apply(this, arguments);
- // };
- object.prototype.base = function() { // 用于调用基类的构造函数
- var Base = this.type.Base; // 第2层构造函数
- if (!Base.Base) { // 如果基类没有基类
- Base.apply(this, arguments); // 就直接调用基类的构造函数
- } else { // 如果基类上面还有基类
- this.base = makeBase_(Base); // 先覆盖this.base,返回一个函数
- Base.apply(this, arguments); // 然后调用基类构造函数,其调用this.base
- delete this.base;
- }
- function makeBase_(Type) { // 包装基类构造函数
- var Base = Type.Base; // 第3层构造函数
- if (!Base.Base) return Base; // 不存在基类,直接返回
- return function() { // 包装为引用临时变量Base的闭包函数
- this.base = makeBase_(Base); // 先覆写this.base
- Base.apply(this, arguments); // 再调用基类的构造函数
- };
- }
- };
- // 定义类的语法甘露:Class()
- // 最后一个参数是JSON表示的类定义
- // 如果参数的数量大于1,则第一个参数是基类
- // 第一个参数和最后一个参数之间,可以表示类实现的接口
- // 返回一个类,类是一个构造函数
- function Class() {
- var aDefind = arguments[arguments.length - 1]; // 类定义
- if (!aDefind) return;
- // 确定基类,默认是object基本类
- // aBase 是一个构造函数,会继承它的原型对象
- var aBase = arguments.length > 1 ? arguments[0] : object;
- function prototype_() {} // 临时函数, 用于挂接原型链
- prototype_.prototype = aBase.prototype; // 准备传递prototype
- aPrototype = new prototype_(); // 建立类要用的prototype
- // 复制类定义到当前类的原型prototype上
- for (var member in aDefind) {
- if (member != 'create') // 不复制构造函数create
- aPrototype[member] = aDefind[member];
- }
- // 处理不可枚举的内置方法
- if (aDefind.toString !== Object.prototype.toString) {
- aPrototype['toString'] = aDefind.toString;
- }
- if (aDefind.valueOf !== Object.prototype.valueOf) {
- aPrototype['valueOf'] = aDefind.valueOf;
- }
- if (aDefind.toJSON !== Object.prototype.toJSON) {
- aPrototype['toJSON'] = aDefind.toJSON;
- }
- var aType; // 存放构造函数的引用
- if (aDefind.create) aType = aDefind.create; // 类型即为该构造函数
- else aType = function() { // 如果未定义create(), 使用默认构造函数
- this.base.apply(this, arguments); // 调用基类的构造函数
- }
- aType.prototype = aPrototype; // 设置类的prototype
- aType.Base = aBase; // 设置类型关系
- aType.prototype.Type = aType; // 为本类对象扩展一个Type属性
- return aType; // 返回构造函数作为类
- }
来源: http://lib.csdn.net/snippet/javascript/43439