A
A
Alexey2018-06-21 12:53:24
JavaScript
Alexey, 2018-06-21 12:53:24

Passing an object by reference, working with memory?

I read https://learn.javascript.ru/object-reference, but I still have questions, I hope you can help me figure it out.
On the server node with a socket. Let's say we have:

var globalVariable = {
    user111: {
      id: 111,
      name: 'Vasya'
    },
    user222: {
      id: 222,
      name: 'Petya'
    }
  };
  //слушаем ивент на ренейм юзера
  .on('rename', obj => {
    //где obj = { id: [user_id], newName: [string] }
    //изменяем глобальный объект, ссылкой на вновь прибывший ?
    globalVariable['user'+obj.id].name = obj.newName;
  });

There are several questions:
1. Will the garbage collector be able to pick up exactly this obj or will it wait until a new request for the same user arrives, will it hang in memory?
2. what will happen if this object is nullified (obj = null) after assignment to the global object? and is it right to do so?
3. or I misunderstood everything and it assigns only a string (obj.newName), and not a link to a property of this object?
4. how to correctly assign objects to a global object so that there are no references to it? Example:
//у юзера есть еще свойство customObj, который является объектом
  .on('someEvent', obj => {
//где obj = { propone: 'someValue', proptwo: 'someValue' }
//предположим что каким-то магическим образом знаем ид юзера
  globalVariable.user111.customObj = obj;
});

If there are relatively many such users, it will probably gobble up all the memory, how to be?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2018-06-21
@Casufi

Objects are assigned by reference, simple types are assigned by value.
If obj.newName is a string, then globalVariable['user'+obj.id].name will be set to a string
Second case, obj.newName is an object, in which case globalVariable['user'+obj.id].name will be set to a reference to the newName object itself, the fact that this object can be simultaneously a property of obj does not prevent the obj garbage collector from removing it.
In this particular case, assigning obj = null would just be an extra useless operation.
how to correctly assign objects to a global object so that there are no references to it? Example:
This is a very general question and there is no short answer.

after all, it will gobble up all the memory, as
too, too childish statement, in relation specifically to your piece of code.
In addition, "Global Object" is some kind of dumb concept, and using global variables in code is fraught with an architecture of shit and stilts.
Read the full https://www.ozon.ru/context/detail/id/19677670/ and not just one chapter on the site, then the questions will become more specific.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question