Create an object based on 2 others

Possible Duplicate:
How can I merge properties of two JavaScript objects dynamically?

I have two objects a and b defined like this:

a = { 
  a: 1, 
  af: function() { console.log(this.a) }, 
};
b = { 
  b: 2, 
  bf: function() { console.log(this.b) },
};

What I want now is to create another object which will get the properties of a and b, like this:

c = { 
  a: 1, 
  af: function() { console.log(this.a) },
  b: 2, 
  bf: function() { console.log(this.b) },
}

Note that a and b need to stay the same.

Any idea of how to do this ?


You could do a for in loop for both a and b, and copy all hasOwn properties to a new object.

var c = {};
for (var p in a)
    if(a.hasOwnProperty(p))
         c[p] = a[p];
for (var p in b)
    if(b.hasOwnProperty(p))
         c[p] = b[p];

DEMO


Or, if you happen to be using jQuery, you could do:

var c = $.extend({}, a, b);

var desc    = Object.getOwnPropertyDescriptor,
    props   = Object.getOwnPropertyNames,
    define  = Object.defineProperty;

function extend( target ) {
    return {
        with: function( source ) {
            props( source ).forEach(function( key ) {
                define( target, key, desc( source, key ) );
            });
        }
    };
}

So now we can go like

var c = Object.create( null );

extend( c ).with( a );
extend( c ).with( b );

Disclaimer: the provided codes assume we are in a ES5 or ES5 shimed environment !


var i, c={};
for (i in a) { if (a.hasOwnProperty(i)) { c[i] = a[i]; } }
for (i in b) { if (b.hasOwnProperty(i)) { c[i] = b[i]; } }

您可以将此功能抽象为您自己的“扩展”功能,类似于jQuery提供的功能:

function extend() {
  var i, j, x, o=(arguments[0] || {});
  for (i=1; i<arguments.length; i++) {
    x = arguments[i];
    for (j in x) { if (x.hasOwnProperty(j)) { o[j] = x[j]; } }
  }
  return o;
}
var c = extend({}, a, b);
链接地址: http://www.djcxy.com/p/27348.html

上一篇: 如何在jquery中合并两个数组对象元素

下一篇: 基于2个其他创建一个对象