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 Answer 1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.