JavaScript类继承实现之一

JavaScript的类默认是通过原型对象继承:

var Person = function() {
    this.name = "people";
    this.hello = function() {
      console.log("hello user:" + this.name);
    }
}

var User = function() {
    this.name = "user";
    this.hello = function() {
      User.prototype.hello.call(this, arguments);
      console.log("hello user:" + this.name);
    }
}

User.prototype = new Person();
new User().hello();
有没有一种方法,能够让JavaScript的类像Java那样,通过一个super关键字即调用父类的方法,于是我这样扩展了Function:

(function() {
    Function.prototype.extend = function(baseClass) {

        // this is a function object.
        var oldPrototype = this.prototype, newPrototype = {}, _super = new baseClass();

        //inherits all properties and methods.
        for ( var name in _super) {
            newPrototype[name] = _super[name];
        }

        for ( var name in oldPrototype) {
            // only override properties in this new Class.
            if (oldPrototype.hasOwnProperty(name)) {
                // only function need _super.
                if (typeof oldPrototype[name] == "function" && typeof _super[name] == "function") {
                    newPrototype[name] =  (function(name, fn) {
                            return function() {
                                var tmp = this._super;
                                
                                // set super method
                                this._super = _super[name];

                                var ret = fn.apply(this, arguments);
            
                                this._super = tmp;
            
                                return ret;
                            };
                        })(name, oldPrototype[name]);
                } else {
                    newPrototype[name] = oldPrototype[name];
                }
            }
        }

        this.prototype = newPrototype;
        
        return this;
    };
})();
测试代码
var A = function() {
    this.hello = function() {
        console.log("hello, I'm A");
    }
};

var B = function() {};

B.prototype = {
    hello : function() {
        this._super();

        console.log("hello, I'm B");
    }
};

B.extend(A);

var C = function() {};

C.prototype = {
    hello : function() {
        this._super();

        console.log("hello, I'm C");
    }
};

C.extend(B);

var b = new B();
var c = new C();

//b.hello();
c.hello();

结果

hello, I'm A
hello, I'm B
hello, I'm C




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值