动态父类调用:
一次性支持代码:
//定义最顶级类function Class() { }Class.prototype.construct = function() {};Class.__asMethod__ = function(func, superClass) { return function() { var currentSuperClass = this.$; this.$ = superClass; var ret = func.apply(this, arguments); this.$ = currentSuperClass; return ret; };};Class.extend = function(def) { var classDef = function() { if (arguments[0] !== Class) { this.construct.apply(this, arguments); } }; var proto = new this(Class); var superClass = this.prototype; for (var n in def) { var item = def[n]; if (item instanceof Function) { item = Class.__asMethod__(item, superClass); } proto[n] = item; } proto.$ = superClass; classDef.prototype = proto; //赋给这个新的子类同样的静态extend方法 classDef.extend = this.extend; return classDef;}; 运行示例:
//Hey, 注意一下这个类的定义方式//看上去比其它方式要清楚些var BaseClass = Class.extend({ construct: function() { /* optional constructor method */ }, getName: function() { return "BaseClass(" + this.getId() + ")"; }, getId: function() { return 1; }});var SubClass = BaseClass.extend({ getName: function() { //调用BaseClass的getName()方法 return "SubClass(" + this.getId() + ") extends " + this.$.getName.call(this); }, getId: function() { return 2; }});var TopClass = SubClass.extend({ getName: function() { //调用SubClass的getName()方法 return "TopClass(" + this.getId() + ") extends " + this.$.getName.call(this); }, getId: function() { //this.getId()总是返回调用父类的getId()方法的返回值(2) return this.$.getId.call(this); }});//输出结果:"TopClass(2) extends SubClass(2) extends BaseClass(2)"//一切都正确!alert(new TopClass().getName())