0

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?, answers like https://stackoverflow.com/a/509614/1117796 and posts like 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;. Is it at all possible? Anything that comes near to it?

Community
  • 1
  • 1
SBhojani
  • 499
  • 1
  • 4
  • 19

3 Answers3

0

No, this is not possible as of ECMA Script 5.

kamituel
  • 34,606
  • 6
  • 81
  • 98
0

No its not possible. And its a boon that this is not allowed in JavaScript.

Hrishi
  • 7,110
  • 5
  • 27
  • 26
0

No that isin't possible to pass simple values as reference in 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. That could work for global variables however, there's no way to completely mimic this behaviour. 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.

plalx
  • 42,889
  • 6
  • 74
  • 90