2016-07-14 134 views
-1

是否有某种某种“共享”变量的方式?我想要做的是这样的:node.js如何使一个变量适用于另一个变量?

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 
+3

你试过吗?我很确定这应该工作,因为对象通过引用传递。 –

+0

还没有尝试过,因为它对我来说甚至不合逻辑 – Donatas

+0

在询问它之前尝试一个示例是一个好主意。 –

回答

0

在JavaScript中,您不直接将对象存储在变量中,而是存储对象的引用。

这意味着,你可以有两个变量指向同一个对象 - 你只需复制参考:

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

在这种情况下,如果您通过a变异的对象,后来通过b读它,你会看到变化。

有了正确实施Player,可以使这项工作对您:

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.

相关问题