Donatas
Donatas

Reputation: 111

node.js how to make one variable change apply to another one aswell?

Is there some kind of way of having some kind of "shared" variable? What I want to do is this:

var id = 5;
var player = new Player(id);

var array1[0] = player;
var array2[0] = player;

array1[0].id = 8

console.log(array1[0]); //8
console.log(array2[0]); //8

Upvotes: 0

Views: 275

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42460

In JavaScript, you do not store an object directly in a variable, but rather a reference to the object.

That means, you can have two variables that point to the same object - you simply copy the reference:

var a = {test: "test"};
var b = a;
console.log(a === b) // true

In this case, if you mutate the object via a and later read it via b, you will see the changes.

With the right implementation of Player, you can make that work for you:

var Player = function(id) {
  this.id = id;
}
Player.prototype.setId = function(id) {
  this.id = id;
}
Player.prototype.getId = function() {
  return this.id;
}

var player = new Player(5);

console.log(player.getId()); // 5

var arrA = [];
var arrB = [];

arrA.push(player);
arrB.push(player);

console.log(arrA[0].getId()); // 5
console.log(arrB[0].getId()); // 5

arrA[0].setId(10);

console.log(arrA[0].getId()); // 10
console.log(arrB[0].getId()); // 10

Check MDN for more info on working with objects.

Upvotes: 2

Related Questions