[英]Assign var by reference - JavaScript
My question is simple but I have not found anything like my problem. 我的问题很简单,但是我没有发现任何类似的问题。 The closest is the singleton pattern but not what I need.
最接近的是单例模式,但不是我所需要的。
I would do something like this in JavaScript: 我会在JavaScript中执行以下操作:
var a = b = c = 0;
Thereby that: 从而:
c = 3.141516;
console.log(b); // 3.141516
console.log(a); // 3.141516
b = 'Hello World';
console.log(c); // 3.141516
console.log(a); // Hello World
In PHP there is a operator =&
works just like I want. 在PHP中,有一个运算符
=&
就像我想要的那样工作。
There is no "assignment by reference" in JavaScript. JavaScript中没有“按引用分配” 。 The closest you'll get will look something like this:
您将获得的最接近的外观如下所示:
var a = b = c = {};
c.foo = 3.141516;
console.log(a.foo); // 3.141516
console.log(b.foo); // 3.141516
b.foo = 'Hello World';
console.log(a.foo); // 'Hello World'
console.log(b.foo); // 'Hello World'
The variables a
, b
, and c
all reference the same object, so that when you change a property on that object, the 3 references to that object all see the same change. 变量
a
, b
和c
都引用相同的对象,因此,当您更改该对象的属性时,对该对象的3个引用都将看到相同的更改。
I assume that the console.log(c)
line in the example in your question is a copy-paste error, and that you expect it to print 'Hello World'
, not 3.141516
. 我假设问题示例中的
console.log(c)
行是复制粘贴错误,并且您希望它显示'Hello World'
,而不是3.141516
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.