-
When passing objects as parameters, JavaScript passes them by reference and makes it hard to create local copies of the objects.
var o = {}; (function(x){ var obj = x; obj.foo = 'foo'; obj.bar = 'bar'; })(o)owill have.fooand.bar. -
It’s possible to get around this by cloning; simple example:
var o = {}; function Clone(x) { for(p in x) this[p] = (typeof(x[p]) == 'object')? new Clone(x[p]) : x[p]; } (function(x){ var obj = new Clone(x); obj.foo = 'foo'; obj.bar = 'bar'; })(o)owill not have.fooor.bar.
Question
- Is there a better way to pass objects by value, other than creating a local copy/clone?
Not really.
Depending on what you actually need, one possibility may be to set
oas the prototype of a new object.So any properties you add to
objwill be not be added too. Any properties added toobjwith the same property name as a property inowill shadow theoproperty.Of course, any properties added to
owill be available fromobjif they’re not shadowed, and all objects that haveoin the prototype chain will see the same updates too.Also, if
objhas a property that references another object, like an Array, you’ll need to be sure to shadow that object before adding members to the object, otherwise, those members will be added toobj, and will be shared among all objects that haveobjin the prototype chain.Here you can see that because you didn’t shadow the Array at
bazonowith abazproperty onobj, theo.bazArray gets modified.So instead, you’d need to shadow it first: