0

What is the reference in object and how to see the reference allocated to the object in javascript.I used lodash _.clone() in an object and i made a example bellow

var  Obj = {id : 0, box: 0, ei : 0};
        var model = {id : 0,ob : [{c: 1, a: 0}],com: _.clone(Obj)};
        var old=_.clone(model)
        old.id=1;
        console.log(old.id===model.id); //false correct
        old.com.id=1;
        console.log(old.com.id===model.com.id);//true

while updating the old.id as 1 the model id has not updated,But while updating the old.com.id as 1 now the model.com.id has also updated why?

  • *What is the reference in object*, objects are assigned using reference. So when you do `var a = {}`, a will hold the memory location and not `{}`. *how to see the reference allocated to the object* You cannot, as far as I know. *model.com.id has also updated why?* because, _.clone does not do a deep copy. It copies only first level – Rajesh Nov 29 '17 at 05:13
  • You can refer this for options for deep copy: https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Rajesh Nov 29 '17 at 05:15

1 Answers1

0

_.clone does a shallow copy. This means that it creates a new object, then for every value in the old object, it assigns the same value to the new object. For primitives (booleans, numbers, strings), this means it's copied. This is necessary so many different references can all have a value of "1" but when one of them is updated they don't all get updated. If it's a reference (Objects and Arrays), the assigned value and the original now refer to the same thing. These rules are true any time you assign something.

For example:

var a = {value:1} 
var b = {value:2} 
a.b = b // this sets the property "b" in a to the reference of the 'b' object. 
// so a.b and b now reference the same object
// so "a.b.value" is the *same* location in memory as "b.value"
// so if you update a.b.value or b.value you'll see it change in both references (because they are the same)

This "same spot in memory" is the key. Continuing the example:

var c = _.clone(a) 

// these three lines are equivalent to the line above
var c = {}
c.value = a.value
c.b = a.b

// "c.b.value" is the "same spot in memory" as "a.b.value" and "b.value"
// So when you set it to a new value that value will change for all objects
// but "a.value" was just copied to c when it was created 
// So "c.value" and "a.value" are different spots in memory
// So changing "c.value" has no effect on "a.value"

Sorry if the comments are a bit hard to read but I think it helps to see it one line at a time versus a stream of sentences.