0

Is it possible to define a variable C to be a combination of 2 objects(let's say A and B), so that anything happens to A and B at any time in the future will happen to C. This means, C is declared before any change to A and B. For example:

var A = {};
var B = {};
var C = combine(A, B);

A.a=1;
B.b=2;

console.log(C);
// { a:1, b:2 }
bjb568
  • 11,089
  • 11
  • 50
  • 71
Maria
  • 3,455
  • 7
  • 34
  • 47
  • 1
    possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – Jeremy J Starcher Aug 16 '14 at 22:08
  • Um.. with your updated question *and in the future* -- that just ain't gunna happen. If you limit yourself to a handful of restricted property names, you could play games with creating an subscriber/publisher pattern and then use the ES5 getters/setters to push changes out -- but dang. No. – Jeremy J Starcher Aug 16 '14 at 22:14
  • 1
    Not a dup--this is asking for dynamic updating. –  Aug 17 '14 at 04:51

1 Answers1

2

C would have to be a function:

function extend(obj) {
    if (typeof obj !== 'object') return obj;
    Array.prototype.slice.call(arguments, 1).forEach(function (source) {
        for (var prop in source) {
            obj[prop] = source[prop];
        }
    });
    return obj;
};

var A = {};
var B = {};
var C = function () {
    var _c = {};
    return extend(_c, A, B);
};

Then call C like:

A.a=1;
B.b=2;

console.log(C());
// { a:1, b:2 }
cuth
  • 514
  • 6
  • 8