How to create a pointer to an object property in javascript?

If I have an object like this:

obj = {a:{aa:1}, b:2};

and I want to create a shortcut (pointer to obj.a.aa) x as follows:

x = obj.a.aa;

and then I want to assign the value 3 obj.a.aa using x, like this:

x = 3;  // I would like for obj.a.aa to now equal 3
console.log(obj.a.aa); // 1  (I want 3)

How can I set x to get the value 3 included in obj.a.aa?

I understand that obj.a.aa is primitive, but how can I define a variable that points to this, which I can then use to assign a value to the property?

+4
source share
3 answers

You cannot use the value x =, as this will not contain any references, just a copy. To do this, you will need to reference the parent branch:

x = obj.a;

then set the value:

x.aa = 3;
+7
source

:

var set_x = function(val){
  obj.a.aa = val;
}
+3

Of course, you cannot - you are not trying to change the link, which is the name of the property of the object, you are trying to change the object . To modify an object, you will need a reference to the object.

This suggests that perhaps this is a creative way to do this. Create a function that takes an object as a constructor, and give the functions to the client a =setter or method that modifies the reference to the object. Maybe something like this.

0
source

Source: https://habr.com/ru/post/1538436/


All Articles