JavaScript实现类效果

Posted by Sir0xb on 2016-01-27 11:00:00 +0800

类的定义:

var Clazz = (function () {
    var Clazz = function () { },
        initializing = false
        superPattern = /xyz/.test(function() { xyz; }) ? /\b_super\b/ : /.*/;
 
    Clazz.create = function (properties) {
        var _super = this.prototype;
        initializing = true;
        var proto = new this();
        initializing = false;
 
        for (var name in properties) {
            proto[name] = typeof properties[name] == "function" &&
            typeof _super[name] == "function" && superPattern.test(properties[name]) ?
                (function(name, fn) {
                    return function() {
                        var tmp     = this._super;
                        this._super = _super[name];
                        var ret     = fn.apply(this, arguments);
                        this._super = tmp;
                        return ret;
                    };
                })(name, properties[name]) : properties[name];
        }
 
        function _Clazz() {
            if (!initializing && this.init) {
                this.init.apply(this, arguments);
            }
        }
 
        _Clazz.prototype     = proto;
        _Clazz.constructor   = Clazz;
        _Clazz.create        = arguments.callee;
 
        return _Clazz;
    }
 
    return Clazz;
}());

 

类的使用:

var Person = Clazz.create({
    init: function (isDancing) {
        this.dancing = isDancing;
    },
    dance: function () {
        return this.dancing;
    }
});
 
var Child = Person.create({
    init: function () {
        this._super(false);
    },
    dance: function () {
        return this._super();
    },
    swiming: function () {
        return true;
    }
});
 
var person = new Person(true);
var child = new Child();
 
console.log('家长能跳舞.');
console.log(person.dance());
 
console.log('孩子能游泳');
console.log(child.swiming());
 
console.log('孩子不会跳舞.');
console.log(child.dance());
 
console.log('家长是人类.');
console.log(person instanceof Person);
 
console.log('孩子也是人类.');
console.log(child instanceof Child && child instanceof Person);

Copyright © 2022, Built with Gatsby