14

I have a global JavaScript object with multiple properties and functions that I am creating it this way:

myObject = {};

I thought that I can easily extend this object by creating something like this

myObject = { propA1 : null, ....., propAN : null};

instead of

myObject.propA1 = null;
myObject......;
myObject.propAN = null;

What's wrong with my approach?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user385411
  • 1,445
  • 1
  • 18
  • 35

3 Answers3

14

When you write myObject = { ... }, you're creating a brand-new object and setting myObject to point to it.
The previous value of myObject is thrown away.

Instead, you can use jQuery:

jQuery.extend(myObject, { newProperty: whatever });
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I guess I should go with this solution but I am wondering how expensive it is. My object is very heavy – user385411 Apr 07 '11 at 18:09
  • @user: This doesn't create any copies; it simply assigns references. It should be fast. – SLaks Apr 07 '11 at 18:22
  • 4
    OP asked about Javascript, not jquery. It also takes away from truely learning Javascript objects. – dman Jan 06 '14 at 02:26
13

Without jQuery, you could create an array of objects with something like this:

[{'key': 'atuhoetu', 'value': 'uehtnehatn'},{...}]

If you don't care about compatibility, recent browsers should support this:

var newObj = {prop1: 'val', prop2: 'val'};
Object.keys(newObj).forEach(function (item) {
    myObject[item] = newObj[item];
});

This will iterate over all items in newObject and add them to myObj.

beatgammit
  • 19,817
  • 19
  • 86
  • 129
  • 1
    Very elegant solution but I guess jQuery Extend is doing the same – user385411 Apr 07 '11 at 18:10
  • 3
    Yeah, I guess it just depends on if you're using jQuery. I use server-side javascript, and this allows code to be used on the server AND the client... – beatgammit Apr 07 '11 at 18:14
  • 1
    Thank you. I am already using jQuery anyway. Actually, I was looking for the concept of partial class that we have .NET so I can spread the same object in multiple files. – user385411 Apr 07 '11 at 18:22
2

Or, something cleaner:

function extend(target, source){
    for(prop in source){
        target[prop] = source[prop];
    }
}

If you use it the following way:

var objA = {a: "a"};
var objB = {b: "b", c: "c"};
extend(objA, objB);

The result will be:

objA = {a: "a", b: "b", c: "c"};