0

In the following script I can't understand why the property prop in the object global is changed by changing the local (private) object local?

var global = {}
global.prop = "Global init";

var ChangeState = (function () {    
var local = global;
local.prop = "Changed"; // expecting Global init?

})()

alert("Global = " + global.prop)

I am not asking JS to change global, but it changes it anyway? Please help.

1 Answers1

1

The value of global is a reference to an object.

Inside your function, you copy that reference to local.

You then change the value of the prop property of that object.

Since global and local reference the same object, global.prop and local.prop will always be the same value.

See this other question for details on how to create a copy of an object instead of a copy of the reference.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335