日期:2014-05-16  浏览次数:20334 次

JS 面向对象 继承与重写
习惯于面向对象的编程方式,对继承一定不陌生,在JS,如何实现呢?
参考EXTJS
Cooker.apply(Cooker, {
	
	  /**
	   * 扩展 
	   *  
	   * @param {Function} subclass
       * @param {Function} superclass
       * @param {Object} overrides
       * @return {Function} 扩展后的对象
	   */
    extend: (function() {
        var  inlineOverrides = function(o) {
            for (var m in o) {
                if (!o.hasOwnProperty(m)) {
                    continue;
                }
                this[m] = o[m];
            }
        };

        return function(subclass, superclass, overrides) {
        	var objectConstructor = Object.prototype.constructor;
            if (Cooker.isObject(superclass)) {
                overrides = superclass;
                superclass = subclass;
                subclass = overrides.constructor !==  objectConstructor? overrides.constructor : function() {
                    superclass.apply(this, arguments);
                };
            }

            var F = function() {},
                subclassProto, superclassProto = superclass.prototype;

            F.prototype = superclassProto;
            //设置子类对象的原型
            subclassProto = subclass.prototype = new F();
            //
            subclassProto.constructor = subclass;
            //
            subclass.superclass = superclassProto;

            if (superclassProto.constructor === objectConstructor) {
                superclassProto.constructor = superclass;
            }

            subclass.override = function(overrides) {
                Cooker.override(subclass, overrides);
            };

            subclassProto.override = inlineOverrides;
            //
            subclassProto.proto = subclassProto;

            subclass.override(overrides);
            subclass.extend = function(o) {
                return Cooker.extend(subclass, o);
            };

            return subclass;
        };
    })(),
	/**
	 * 
	 * 重写
	 * 
	 * @param target: 要重写的对象
	 * @param overrides:要重写/追加的属性
	 * 
	 */
	override: function(target, overrides){
	    if(target){
	        var p = target.prototype;
	        for(var method in overrides){
	            p[method] = overrides[method];
	        }
	    }
	}
});