原生js实现的class

源码如下:

var Class = Object.defineProperties(new Function(), {
    extend: {//继承
        value: function (mate) {
            var child = function () {
                this.ctor.apply(this, arguments);
            };
            for (var a in mate) {
                if (typeof mate[a] === "function") {
                    (function (__name__, __fun__) {
                        mate[__name__] = function () {
                            var m = this.__mate__, n = this.__name__;
                            this.__mate__ = mate, this.__name__ = __name__;
                            var r = __fun__.apply(this, arguments);
                            this.__mate__ = m, this.__name__ = n;
                            return r;
                        };
                    })(a, mate[a]);
                }
            }
            mate.__proto__ = this;
            child.prototype = mate;
            child.extend = Class.extend.bind(mate);
            return child;
        }
    },
    _super: {//所有子类的super方法
        value: function () {
            this.__mate__.__proto__[this.__name__].apply(this, arguments);
        }
    }
});
Class.prototype = Class.__proto__ = new Object(); //不影响使用,可用于 child instanceof Class

使用方法:

var Parent = Class.extend({
    ctor: function (name) {
        this._name = name;
    },
    test: function (data) {
        console.log("Parent:", data);
    }
});
var Child = Parent.extend({
    ctor: function (name) {
        this._super(name);
        console.log(this._name);
    },
    test: function () {
        this._super(new Date().getTime());
        console.log(this instanceof Object, this instanceof Class, this instanceof Parent, this instanceof Child);//true
        console.log(this instanceof Parent.extend({ctor: function () {}}), this instanceof Array);//false
    }
});
var child = new Child("dfsdf");
child.test();
console.log(Object.getOwnPropertyDescriptors(new Function()));

简介:Class可被无限级继承,任意层级必须包含ctor方法,子对象任何方法内可以通过 this._super() 调用最近的上级父类同名方法

子对象内不可使用 arguments、caller、length、name这几个字段子对象内不可使用 arguments、caller、length、name这几个字段

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值