Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending an object with multiple properties in JavaScript

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?

like image 959
user385411 Avatar asked Apr 07 '11 17:04

user385411


People also ask

How many properties can a JavaScript object have?

How many properties can an object have JS? Summary. JavaScript objects have two types of properties: data properties and accessor properties.

How do you extend an object in JavaScript?

The extends keyword can be used to extend the objects as well as classes in JavaScript. It is usually used to create a class which is child of another class. Syntax: class childclass extends parentclass {...}

How do you add properties to an existing object?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.

How do you concatenate an object?

JavaScript concat() Method : Array ObjectThe concat() method is used to join two or more arrays. Concat does not alter the original arrays, it returns a copy of the same elements combined from the original arrays. arrayname1, arrayname2, ..., arraynameN : Arrays to be joined to an array.


1 Answers

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 });
like image 107
SLaks Avatar answered Oct 14 '22 16:10

SLaks