[英]Any way to assign a variable (not an object property) another variable's value by reference in JavaScript?
So, here's what I need: 所以,这就是我需要的:
var a = 5;
var b = a;
a = 6;
alert(b) // I want this to alert 6 not 5
I've seen questions like How does variable assignment work in JavaScript? 我曾经看到过诸如JavaScript中的变量分配如何工作之类的问题? , answers like https://stackoverflow.com/a/509614/1117796 and posts like http://hpyblg.wordpress.com/2010/05/30/simulating-pointers-in-javascript/ .
,例如https://stackoverflow.com/a/509614/1117796之类的答案,以及http://hpyblg.wordpress.com/2010/05/30/simulating-pointers-in-javascript/之类的帖子。 I do NOT want to use objects/hashes/dictionaries or whatever else you want to call them.
我不想使用对象/哈希/字典或其他任何您想调用的对象。 I want this done with plain variables containing plain primitive values.
我希望通过包含普通原始值的普通变量来完成此操作。 Something like the PHP assignment by reference:
$b = &$a;
类似于通过引用分配的PHP:
$b = &$a;
. 。 Is it at all possible?
有可能吗? Anything that comes near to it?
有什么接近的吗?
不,从ECMA Script 5开始这是不可能的。
No its not possible. 没有不可能。 And its a boon that this is not allowed in JavaScript.
而且,这是JavaScript不允许的。
No that isin't possible to pass simple values as reference in JavaScript. 没有,不可能在JavaScript中传递简单值作为参考。
However JavaScript is a flexible language and you could possibly implement something similar using Object.defineProperty
by providing setters and getters that will all work with the same variable. 但是JavaScript是一种灵活的语言,您可以使用
Object.defineProperty
来实现相似的功能, Object.defineProperty
是提供设置器和Object.defineProperty
器,它们都将使用相同的变量。 That could work for global
variables however, there's no way to completely mimic this behaviour. 这可能适用于
global
变量,但是,没有办法完全模仿这种行为。 For instance, since you can't get a reference to the execution scope of functions, you would not be able to emulate this concept for variables declared inside functions. 例如,由于您无法获得对函数执行范围的引用,因此您将无法在函数内部声明的变量上模仿此概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.