实现super

2020-08-11  本文已影响0人  zhulichao
```
Object.prototype.mysuper = function(){
    // 返回一个对函数的引用,该函数调用了当前函数,不能使用arguments.callee.name,arguments.callee.name的值为mysuper
    var caller = arguments.callee.caller;
    var name;
    for(var key in this){
        if(this[key] === caller){
            name = key;
            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;
    }
    this.method = function() {
        console.log("父类方法");
    };
}
function Test(){
    this.getName = function(){
        return 'sub-' +  this.mysuper();
    }
    this.method = function() {
        this.mysuper();
    }
}
// 实现继承
Test.prototype = new Class();
Test.prototype.constructor = Test;

var a = new Test();
console.log(a.getName()); // sub-class
a.method(); // 父类方法
```
上一篇 下一篇

猜你喜欢

热点阅读