Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript reference drop

Tags:

javascript

I'm creating a module that extends existing application. I've received a variable device and I want to create myDevice that will always hold the same data. Lets say that data is contained in an array:

https://jsfiddle.net/hmkg9q60/2/

var device = {
  name: "one",
  data: [1, 2, 3]
};
var myDevice = {
  name: "two",
  data: []
};

myDevice.data = device.data; // Assign array reference


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

console.log(device.data); // [1, 2, 3, 4]
console.log(myDevice.data); // [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.data); // [1, 2, 3, 4] - I would like to get [0,0,0]

What I would like to obtain is to be sure, that myDevice will always hold the same data as device, even if someone decides to use the assign operator somewhere in the application. I don't want to clone myDevice because I want to hold "name" and other properties.

Is there a way in JavaScript to create such reference to an object field?

like image 588
JoshThunar Avatar asked Jun 11 '19 11:06

JoshThunar


1 Answers

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);
like image 180
Matt Ellen Avatar answered Oct 21 '22 10:10

Matt Ellen