我的Javascript的O-O实现

我的Javascript的O-O实现

function _class(cls) {
    var result = function () {
        !this.hasOwnProperty('upper') && (this.upper = function () {
            return result.prototype;
        });
        cls.apply(this, arguments);
    };

    result.inherit = function (_super) {
        // _super must be made by _class
        this.prototype = new _super();
        return this;
    };
    return result;
}

用法


var Person = _class(function () {
    this.age = 1;
    this.name = 'foo bar';
    this.bucket = {
        v1: 2,
    };

    var _methods = {
        sayHi: function (msg) {
            console.log(this.name + ': ' + msg);
        }
    };
    $.extend(this, _methods);
});

var Soldier = _class(function () {
    this.upper().constructor.apply(this, arguments);

    var _methods = {
        sayHi: function (msg) {
            this.upper().sayHi(msg + ' from soldier');
        }
    };
    $.extend(this, _methods);
});
Soldier.inherit(Person);

如果有兴趣可以参考另外2个实现
2008年John Resig的http://ejohn.org/blog/simple-javascript-inheritance/
Douglas Crockford的http://javascript.crockford.com/inheritance.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值