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

关于apply,把两个对象属性赋给另一个对象
想把两个对象赋给另一个对象,用apply怎么实现?
比如
JScript code

var a = {"A":"a"};
var b = {"B":"b"};
var c;//把a,b赋值给c,让c有"A","B"属性




------解决方案--------------------
var c={};
$.extend(c,a,b);
//---------------------------------

用 apply太绕 还要给a b 对象加方法才行 如下
var a ={a:1,aa:2,aaa:3,extend:function(obj){
for(var name in obj)
this[name] = obj[name];
}},
c ={c:1,cc:2,ccc:3,extend:function(obj){
for(var name in obj)
this[name] = obj[name];
}}
b={};
a.extend.apply(b,[a]);
c.extend.apply(b,[c]);
alert(b.toSource())
------解决方案--------------------
如果有单独的extend函数 是可以不需要 给 a,b加方法的

JScript code
    var extend = function(){
        var target = arguments[0] || {}, i = 1, length = arguments.length, deep = true, options;
        if ( typeof target === "boolean" ) {
            deep = target;
            target = arguments[1] || {};
            i = 2;
        }
        if ( typeof target !== "object" && Object.prototype.toString.call(target)!="[object Function]")
            target = {};
        for(;i<length;i++){
            if ( (options = arguments[ i ]) != null )
                for(var name in options){
                    var src = target[ name ], copy = options[ name ];
                    if ( target === copy )
                        continue;
                    if ( deep && copy && typeof copy === "object" && !copy.nodeType ){
                        target[ name ] = arguments.callee( deep, src || ( copy.length != null ? [ ] : { } ), copy );
                    }   
                    else if(copy !== undefined)
                        target[ name ] = copy;                       
                }
    
        }
        return target;           
    };

    var a ={a:1,aa:2,aaa:3,aaaa: function(){}},
    c ={c:1,cc:2,ccc:3,cccc:function(){}}
    b={};
    extend(b,a,c);
    alert(b.toSource());

------解决方案--------------------
JScript code

var a = {"A":"a"};
var b = {"B":"b"};
var c;
c=a;
for(var i in b){
  c[i] = b[i];
}
console.log(c);

------解决方案--------------------
简单的写了个最暴力的extend
JScript code
var a = {"A":"a"};
var b = {"A":"xxxxx","B":"b"};
function extend(a,b){
    for(var n2 in b){
        a[n2]=b[n2];
    }
    return a;
}
var c=extend(a,b);
alert(c.B);