will this.myObj = myObj store a reference or a copy/snapshot? will this.myObj = myObj store a reference or a copy/snapshot? json json

will this.myObj = myObj store a reference or a copy/snapshot?


It is a reference to the object. There is one object with two ways of "addressing" it.

function Cls(obj) {  this.myObj = obj;}var foo = { bar : 1 }var x = new Cls(foo);foo.bar = 2;console.log(x.myObj) // { bar : 2 }


You are just assigning a reference to an object. After all, you're only dealing with references in ECMAscript. There is no such thing like "the actual object" with that you can deal in memory, or clone it. Well you can clone it, but that would just create another object on the HEAP where you get a reference to.

Think of it like so...

var newObj = { };

What happens now is, that new object is formed/created somewhere on the HEAP and you have a reference to that in your newObj variable. When we go like

newObj.foo = newObj

we are just referencing to the same object, somewhere on the HEAP. No magic at all.


A reference, for sure:

var foo = function () {};var foo_instance = new foo();var bar = {    foo: foo_instance};console.log(foo_instance === bar.foo);    // true

If you want to clone the object, you have two alternatives:

jQuery:

var foo = function () {};var foo_instance = new foo();var foo_instance_clone = new foo();$.extend(foo_instance_clone, foo_instance);

Pure JavaScript:

var foo = function () {};var foo_instance = new foo();var foo_instance_clone = new foo();for (var key in foo_instance) {    if (foo_instance.hasOwnProperty(key)) {        foo_instance_clone[key] = foo_instance;    }}