1

How know js?? :D

    let obj = {}
    let anotherObj = obj 

Now anotherObj contain {} value as reference on obj. So anotherObj has only reference on obj. But when we reassign new value to obj Why assigning in js works in this way? And I know this feature provide usefull monkeypatching technic

    anotherObj // {}
    obj = null
    anotherObj // {}

Variable anotherObj still contain {} value. But anotherObj is a reference on obj and as I understand it should contain null as obj

Nikolay Podolnyy
  • 931
  • 10
  • 19

1 Answers1

1

You're misunderstanding the way that "references" work. You're thinking in terms of pointers like in C. When you see...

var obj = {};
var anotherObj = obj;

...you're thinking obj references an object and anotherObj references obj which references an object. You're thinking in terms of a chain of references. But that's not how assignment works in most languages unless you're using pointers or other address space references.

Instead, what happens is var obj = {}; creates an object in some memory location, and obj now contains that memory location. When you do var anotherObj = obj;, then obj gets evaluated as that memory location and that memory location now gets assigned as the value to anotherObj. So now rather than anotherObj pointing to obj, we have both obj and anotherObj pointing to the same memory location of the obj.

So, when we do obj = null, we're only changing the value that obj points to--anotherObj is still pointing to the memory location of the object we created.

To my knowledge, there's no way to update all of your object references or even to delete the object manually (e.g. replacing it with null like you're trying to do). If your intent is to do something like that for the purpose of managing object life cycle, then you're going to be disappointed. Instead, you're going to need to take an alternative approach like storing the object in a global variable and then using that global reference as opposed to several local references.

B. Fleming
  • 7,170
  • 1
  • 18
  • 36