Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you assign a property to an Object, can you make it changes as the object changes?

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?

like image 420
Loredra L Avatar asked Feb 05 '23 08:02

Loredra L


1 Answers

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());
like image 154
R3tep Avatar answered Feb 16 '23 03:02

R3tep