4

I was testing with the basic with the below code

var A={};
var B={name:"come"};
A.pro=B;
B=null;
//Here A.pro is still point to normal B, not to a null

How should I do this if I want when B changes, A.pro will also change?

Loredra L
  • 1,485
  • 2
  • 16
  • 32
  • That's cause `A.pro` has nothing to do with `B` once it's declared. If you want to change `A.pro` you have to explicitly say so. `A.pro = null` for example. – Baruch May 30 '17 at 14:17
  • might be worth giving a use case or what you are trying to achieve. because there is no reason you'd have that code in a working application its hard to answer in a useful way – atmd May 30 '17 at 14:19
  • Try with `A.bro=()=>B` – prasanth May 30 '17 at 14:20
  • 1
    @atmd, sometimes, you need a reference to an object but, if directly assigned, it would fail, because you need a second reference to it. if you assign the object directly, you could loose the reference to it. practical example [here](https://stackoverflow.com/a/44005308/1447675), where all arrays are wrapped by an object `groups[b] = { values: [] };`. – Nina Scholz May 30 '17 at 14:28
  • `var A = {get pro() { return B; }}`? – Bergi May 30 '17 at 14:45

2 Answers2

5

You can use an anonymous function, like :

var A = {};
var B = {
  name: "come"
};

A.pro = function() {
  return B
};

// or with arrow function
// A.pro = () => B;

B = null;
console.log(A.pro());

Other way

If you want to update B value with A.pro(), you can use an optional parameter, like :

var A = {};
var B = {
  name: "come"
};

A.pro = function(newVal) {
  (typeof newVal === 'undefined') ? false : (B = newVal);
  return B;
};

B = null;
console.log(A.pro());
A.pro(4);
console.log(A.pro());
R3tep
  • 12,512
  • 10
  • 48
  • 75
3

You could use a nested approach with an additional object.

var a = {},
  b = { data: { name: "come" } };

a.pro = b;
console.log(a);

b.data = null;
console.log(a);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • This one seems really interesting. Do you know why simply add another layer for b would make this work? I mean if there is any principle of Javascript that this belongs to? – Loredra L May 30 '17 at 14:32
  • it is more because of the structure of objects in javascript. if you assign a (primitive) value to an object, the reference to the object `A` stays but `B` in your example has lost the reference. the rule is assigning a new value to an object deletes the reference to a former assigned object. – Nina Scholz May 30 '17 at 14:38