Ext.apply Ext.applyif 的理解

Ext.apply、 Ext.applyIf和Ext.extend:Ext.apply(obj, config, [defaults]) 将config对象的所有属性都复制到另一个对象obj上, 第三个参数defaults可以用来提供默认值, 不过通常指用前两个参数就够了。 这个函数主要用在构造函数中, 用来将配置复制到对象上。
 Ext.applyIf(obj, config) 和Ext.apply的功能类似, 唯一不同的是, 这个函数只会将config对象中有, 而obj对象中没有的属性复制到obj上。 Ext.extend(subclass, superclass, [overrides]) 用来继承已有的类, 通常的使用方法是 var SubClass = function() { SubClass.superclass.constructor.call(this); };
Ext.extend(SubClass, BaseClass, { newMethod : function() {}, overriddenMethod : function() {} };在上面的代码中, SubClass继承自BaseClass, 添加了新的方法newMethod, 重写了overriddenMethod方法。
apply方法的签名为“apply( Object obj, Object config, Object defaults ) : Object”,
第一个参数是要拷贝的目标对象,
第二个参数是拷贝的源对象,
第三个参数是可选的,表示给目标对象提供一个默认值。
可以简单的理解成把第三个参数(如果有的话)及第二个参数中的属性拷贝给第一个参数对象。
Ext源代码如下:
view plaincopy to clipboardprint?
/** 
 * Copies all the properties of config to obj. 
 * @param {Object} obj The receiver of the properties 
 * @param {Object} config The source of the properties 
 * @param {Object} defaults A different object that will also be applied for default values 
 * @return {Object} returns obj 
 * @member Ext apply 
 */ 
Ext.apply = function(o, c, defaults){  
    // no "this" reference for friendly out of scope calls  
    if(defaults){  
        Ext.apply(o, defaults);  
    }  
    if(o && c && typeof c == 'object'){  
        for(var p in c){  
            o[p] = c[p];  
        }  
    }  
    return o;  
}; 
/**
 * Copies all the properties of config to obj.
 * @param {Object} obj The receiver of the properties
 * @param {Object} config The source of the properties
 * @param {Object} defaults A different object that will also be applied for default values
 * @return {Object} returns obj
 * @member Ext apply
 */
Ext.apply = function(o, c, defaults){
    // no "this" reference for friendly out of scope calls
    if(defaults){
        Ext.apply(o, defaults);
    }
    if(o && c && typeof c == 'object'){
        for(var p in c){
            o[p] = c[p];
        }
    }
    return o;
};
另外还有ext.applyif 也是对象克隆,不同的是,克隆的对象并不会覆盖原有属性和方法
具体代码如下:
view plaincopy to clipboardprint?
applyIf : function(o, c){  
          if(o){  
              for(var p in c){  
                  if(!Ext.isDefined(o[p])){  
                      o[p] = c[p];  
                  }  
              }  
          }  
          return o;  
      }, 
posted @ 2012-06-26 10:16  holyes  阅读(580)  评论(0编辑  收藏  举报