JavaScript reference drop

You could use getters and setters, and read and assign directly from and to the device object.

var device = {
  name: "one",
  data: [1, 2, 3]
};
var myDevice = {
  name: "two",
  get data() { return device.data; },
  set data(newdata) { device.data = newdata; },
};

console.log(myDevice.data);
device.data = [4,5,6];
console.log(myDevice.data);


I would use a getter

NOTE: more elegant ES6 solution

var device = {
  name: "one",
  data: [1, 2, 3]
};
var myDevice = {}
myDevice.getData = () => device.data;
myDevice.bla = "bla";

device.data.push(4); // Push works on array reference

console.log(device.data); // [1, 2, 3, 4]
console.log(myDevice.getData()); // [1, 2, 3, 4] - ok


device.data = [0, 0, 0]; // A new array is assigned to 'device'
// and 'myDevice' reference stays with old array

console.log(device.data); // [0, 0, 0] 
console.log(myDevice.getData()); // [1, 2, 3, 4] - I would like to get [0,0,0]

Tags:

Javascript