1

Can anyone shed light on this behavior? and how could a be handled privately as a new object instance? Thanks

var a = {};

var b = function(obj) {
  obj.z = 10;
  return obj;
};

console.log("---");
console.log(a); // a = {}
b(a);
console.log(a); // a = {z: 10} -- why is a affected? it's not a = b(a);
(function(obj){
  obj.x = 9;
  console.log(obj);
})(a);
console.log(a); // a = {z:10, x: 9} -- a is also manipulated, why?

EDIT: Objects are accessed by reference therefore "a" is affected globally. Question is, in a Node.js scenario, these objects could be altered by different users entry points if the instance is not isolated / new. ideas on this?

Sagish
  • 1,065
  • 8
  • 13

1 Answers1

0

When you send the variable a as a parameter to a function, it's not a copy of the object in a that is sent to the function, but a reference to the object.

The parameter obj in the function will be a reference to the same object that the variable a points to. When you change obj in the function, the change affects the object itself. When you later use the variable a to look at the object, you see the changes.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Makes sense, but how could "a" be handled privately as a new object instance, not effecting the reference? – Sagish May 24 '13 at 07:36
  • @SagiIsha: To get separate instances you have to actually create two separate instances, there is no way to automatically clone objects. Some libraries have methods that you can use to clone objects, like the `extend` method in jQuery. – Guffa May 24 '13 at 07:49