js function 继承函数 扩展的对象
define([], function() { var extendsObject = function() { this.into && this.into.apply(this, arguments); this.main && this.main.apply(this, arguments); }; //扩展 var extend = function(option) { for(var i in option) this.prototype[i] = option[i]; }; //继承 var inherit = function(option) { var newExtendsObject = function() { this.into && this.into.apply(this, arguments); this.main && this.main.apply(this, arguments); }; for(var i in this.prototype) newExtendsObject.prototype[i] = this.prototype[i]; newExtendsObject.prototype.constructor = newExtendsObject; newExtendsObject.constructor = this; newExtendsObject.extend = extend; newExtendsObject.inherit = inherit; newExtendsObject.extend(option); return newExtendsObject; }; //调用继承对象的同名函数 var _super = function(param) { var _this = this, func; try { //获取函数名 var name = arguments.callee.caller.name; //获取函数参数 var argu = arguments.callee.caller.arguments; //获取对象的继承对象 var _pro_function_ = arguments.callee.caller._pro_function_; _pro_function_ = _pro_function_ ? _pro_function_.constructor : this.constructor.constructor; //获取继承对象的prototype func = _pro_function_.prototype; //查询继承对象是否存在同名函数 func = func[name]; //将函数的对象函数存放在_pro_function_; func && (func._pro_function_ = _pro_function_); //如果存在同名函数则运行 var ret = func && func.apply(_this, argu); //运行完毕之后消除标记 func && (func._pro_function_ = null); } catch(e) { func && (func._pro_function_ = null); } return ret; } extendsObject.extend = extend; extendsObject.inherit = inherit; var fn = extendsObject.prototype = { super: _super, into: function() { }, main: function() { } }; return extendsObject; })
实现了对象的多重继承特性
//定义一个新的父级对象 var obj = extendsObject.inherit({ //构造函数实现定义变量 into : function(){ this.type = '我们都是测试对象'; this.name = "obj"; this.parent = '我就是爸爸'; }, //获取name getName : function(){ return this.name; }, //获取name getParentName : function(){ return this.parent; }, //获取类型 getType : function(){ return this.type; } }); //定义一个新的子对象继承她 var obj1 = obj.inherit({ into : function(){ this.super(); this.name = "obj1"; this.parent = 'obj'; } }) var a = new obj(); var b = new obj1(); console.log(a.getName()); //obj console.log(b.getName()); //obj1 console.log(a.getParentName()); //我就是爸爸 console.log(b.getParentName()); //obj console.log(a.getType()); //我们都是测试对象 console.log(b.getType()); //我们都是测试对象