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?
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?
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());
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());
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; }