16

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?

2
  • When you say "extend". do you mean to add more properties to the object? Or do you the OOP "extend" meaning "inherit"ed by other objects? Commented Apr 7, 2011 at 17:41
  • I meant the object itself and not the class Commented Apr 7, 2011 at 18:07

4 Answers 4

15

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 });
Sign up to request clarification or add additional context in comments.

3 Comments

I guess I should go with this solution but I am wondering how expensive it is. My object is very heavy
@user: This doesn't create any copies; it simply assigns references. It should be fast.
OP asked about Javascript, not jquery. It also takes away from truely learning Javascript objects.
14

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.

3 Comments

Very elegant solution but I guess jQuery Extend is doing the same
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...
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.
3

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"};

Comments

2

You can use Javascript ... spread operator to extend object with properties from other object

var myObject = { a: '1', b: '2' };
var extendWithObject = { c: '3', d: '4' };

myObject = { ...myObject, ...extendWithObject };

and the result will be

{ a: '1', b: '2', c: '3', d: '4' }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.