If you assign a property to an object, can you change it when the object changes?

I tested the base code using the code below

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 can I do this if I want, when changes in B change, A.pro will also change?

+4
source share
2 answers

You can use an anonymous function, for example:

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

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

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

B = null;
console.log(A.pro());
Run codeHide result

Another way

If you want to update the value Bwith A.pro(), you can use an optional parameter, for example:

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());
Run codeHide result
+5
source

You can 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; }
Run codeHide result
+3
source

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


All Articles