日期:2014-05-16  浏览次数:20485 次

Javascript实现super()。
近日比较蛋疼,突然想起Java中的super很好用,心血来潮就用js模拟了下,欢迎拍砖。(注:由于super是js保留字,所有使用mysuper作为函数名。)
		Object.prototype.mysuper = function(){
var caller = arguments.callee.caller,
name;
for(var i in this){
if(this[i] === caller){
name = i;
break;
}
}
__proto = this.__proto__ || this.constructor.prototype;
return __proto[name]();
}
function Class(){
this.name = "class";
this.setName = function(name){
this.name = name;
}
this.getName = function(){
return this.name;
}
}
function Test(){
this.getName = function(){
return 'sub-' +  this.mysuper();
}
}
Test.prototype = new Class();
Test.prototype.constructor = Test;

var a = new Test();
alert(a.getName());

------解决方案--------------------
引用:
心血来潮随手写的,肯定有bug,就没人拍砖吗。。


想法不错。

js实现面向对象编程模式,其中就需要定义关键字super。

给你看一段代码:实现了super关键字

Fan.package('Fan.test'); // 创建一个包

                // 创建类
Fan.clazz('Fan.test.A', function(){
                      var a = null; // 私有属性

                      this.aa = null; // 共有属性
                      
                      // 构造方法
      this.A = function(_a){
          $super(); // 调用父类构造方法
                          a = _a;
      };

      this.init = function(){
       alert2('A:init');
         };
      this.initEvent = function(){
          alert2('A:initEvent');
          this.show(1);
         };
      this.show = function(){
       alert2('Fan.test.A');
      };
  });

    &nbs