模仿mootools对象创建方法 简单的实现

    var extend = function(destination, source, override) {
        if (override === undefined) override = true;
        for (var property in source) {
            if (!override && typeof(source[property]) == 'function' && destination.hasOwnProperty(property)) {
                destination[property] = (function(name, method) {
                    return function() {
                        this.base = source[name];
                        return method.apply(this, arguments);
                    }
                })(property, destination[property]);
            } else {
                destination[property] = source[property];
            }
        }

        return destination;
    };

    var Class = function(implements) {
        if (typeof implements == 'undefined') return;

        var newClass = function() {
            extend(this, implements);
            this.initialize.apply(this, arguments);
        };

        newClass.prototype.setOptions = function(opts) {
            extend(this.options, opts || {});
            return this;
        };

        return newClass;
    };

    var Tab = new Class({
        options : {
            name : 'test'
        },
        initialize : function(opts) {
            this.setOptions(opts);
            alert(this.options.name);
        },
        show : function() {
            return 'i will show';
        }
    });

    var t = new Tab({ name : 'newName' });
    alert(t.show());

  

欢迎大家给改进意见!

posted @ 2012-03-28 10:57  oneroundseven  阅读(211)  评论(0编辑  收藏  举报