Multiple references to a variable in JavaScript

北城以北 提交于 2019-12-24 15:18:55

问题


Is there any way for a variable to act as a reference to another variable? Could I have multiples variable all hold the same information regarding a single piece of data?

For example:

var foo = "data";
var bar = foo;

// I want this to set both foo & bar to null
foo = null;

console.log(bar); // However, bar is still set to "data"

In C or C++ you're able to get this desired behavior with pointers; having two variables reference the same location in memory.

Is there some way to mimic this behavior in JavaScript?


回答1:


In JavaScript, variables that have objects as their value are actually scalar references (pointers) to objects, so assignment simply copies object references, not the objects themselves. So when you do

var bar = foo;

the value of foo gets copied. This means both foo and bar have copies of the same value.

Even with objects, this won't work

var x = {};
var y = x; // y and x both point to the same object
x = null;
// y still points to the object

Again, x and y are copies of the reference, so both x and y are separate references, each with the same value. But nulling one out does nothing to do the other.

The closest you can get is what @Derek朕會功夫 said, which is to do

var x = {val: 'data'};
var y = x;
delete x.val;
// y.val is now undefined 

And pass x or y around.




回答2:


Yes. Sorta. Object references are similar to pointers in C:

var foo = {value: "data"};
var bar = foo;

foo.value = undefined;
console.log("Value: %s", bar.value);  // undefined



回答3:


No you cannot. If the value is a primitive, the value is copied, and if it's an object the reference is copied.

The only thing you can do is point multiple variables to the same object. However reassigning either variable will not re-assign the other.




回答4:


It happens because of different variables types in JavaScript: primitive and reference. Have a look at this article, section Primitive Types and Reference Types explains it really well https://www.safaribooksonline.com/library/view/javascript-the-definitive/0596101996/ch04.html



来源:https://stackoverflow.com/questions/34344365/multiple-references-to-a-variable-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!