基于现有类构造新类

基于现有类构造新类

本函数是一个前辈所写。

 /**
         *  利用JavaScript中原型特性创建面向对象中的“类”。
         *  所有利用该方法创建的类都要实现或者说存在{@link #init}初始方法。
         <pre><code>
         function Base(){
  }

         Base.prototype = {
    init : function(){
        alert('init');
    },
    say : function(){
        alert('Base');
    },
    
    eat : function(){
        alert('eat');
    }
  };

         var A = Exiu.util.create(Base, {
        say : function(){
            Base.prototype.say.apply(this, arguments);
            alert('A');
        }
  });

         var a = new A();
         a.eat();
         a.say();
         </code></pre>
         * @param {String} [namespace] 名称,包含命名空间,可选
         * @param {Function} superclass 父类,无父类可置空
         * @param {Object} attributes 类(原型)属性,方法集
         * @return {Function} 新类
         */
        create: function () {
            var clazz = (function () {
                this.init.apply(this, arguments);
            });

            if (arguments.length === 0)
                return clazz;

            var absObj, base, type, ags = $.makeArray(arguments);

            if (typeof ags[0] === 'string') {
                type = ags[0];
                base = ags[1];
                ags.shift();
            } else base = ags[0];

            ags.shift();

            if (base)
                base = base.prototype;

            if (base) {
                function Bridge() {
                }

                Bridge.prototype = base;
                clazz.prototype = absObj = new Bridge();
            }

            if (type) {
                absObj.type = type;
                Util.ns(type, clazz);
            }

            for (var i = 0, len = ags.length; i < len; i++)
                absObj = $.extend(absObj, typeof ags[i] === 'function' ? ags[i](base) : ags[i]);

            absObj.constructor = clazz;
            return clazz;
        }

 

请把你的疑问评论在下方。
原文地址:https://www.cnblogs.com/zzcit/p/5672908.html