Reputation: 195
Sorry if this has been asked before, but I need a much more straightforward answer than some of the complex examples I've found in my search...
If I create several global objects, let's say they're named Johnson
, Smith
, etc, and afterwards I push them to a global array called people
, like people[0] = Johnson
, people[1] = Smith
...
Have I simply created a reference to that global object, or some sort of duplicate within the array?
So if I choose to add a new property to every object by iterating over the array, people[i].newProperty
, am I just adding a new property to the original global object, or to the global object and the object within the array?
Secondly, would there be any sort of performance hit when assigning properties through the array versus creating the global objects inside of a single global object at the very beginning, like People.Johnson
? I'm guessing there's no difference, but thought I would throw it out there.
Thanks!
Upvotes: 1
Views: 109
Reputation: 3449
Answering your questions:
Q: Have I simply created a reference to that global object, or some sort of duplicate within the array?
A: You created a reference indeed.
Q: So if I choose to add a new property to every object by iterating over the array, 'people[i].newProperty', am I just adding a new property to the original global object, or to the global object and the object within the array?
A: You are modifying the object and the one within the array, since they are the same.
Q: Secondly, would there be any sort of performance hit when assigning properties through the array versus creating the global objects inside of a single global object at the very beginning, like 'People.Johnson'? I'm guessing there's no difference, but thought I would throw it out there.
A: No, there is no performance difference.
Here are some great references for you to study and understand better this subject of objects in arrays for javascript:
[1] Changing array in JavaScript function changes array outside of function?
[2] is it possible to change values of the array when doing foreach in javascript?
[3] http://orizens.com/wp/topics/javascript-arrays-passing-by-reference-or-by-value/
[4] http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Upvotes: 2