2

I want to be able to have two references to the same primitive value, and any change done via one should be reflected to the other "magically" - i.e. using C code as an example:

// (C code):
int value = 0;
int *p1 = &value;
...
int *p2 = &value;
*p2 = 1;
...
printf("%d", *p1); // gives 1, not 0

The only way I've figured it out so far is by using an extra object indirection:

var a = { valueWrapper: { num: 1, str: 'initial' } };
var b = a;

// change a

a.valueWrapper.num = 2;
a.valueWrapper.str = 'changed';

// show b

console.log(b.valueWrapper.num);
console.log(b.valueWrapper.str);

// outputs:
//
// $ node test.js 
// 2
// changed

Is there a cleaner way?

angularJsNewbie
  • 495
  • 2
  • 8
  • 14
  • Your `valueWrapper` middleman is not required. If an object literal is assigned to `a` and `a` is assigned to `b`, both variables will share a reference to the same object. – Frédéric Hamidi Sep 26 '13 at 07:59
  • I am asking about primitives, though: "two references to the same primitive". – angularJsNewbie Sep 26 '13 at 08:12
  • Indeed, but what would be wrong with `a = { num: 1, str: "initial" }`? Both primitives will be shared among all variables that refer to the same object as `a`. In other words, you only need one wrapper. – Frédéric Hamidi Sep 26 '13 at 08:22
  • Maybe this question "[Primitive value vs Reference value](http://stackoverflow.com/q/13266616/1456376)" and especially [this answer](http://stackoverflow.com/a/13268731/1456376) is helpful. – insertusernamehere Sep 26 '13 at 08:28

2 Answers2

2

In Javascript primitive types such as integers and strings are passed by value. There is no build in method to change that.

You can get rid of "valueWrapper" if it's not by design:

var a = {num :  1, str : "initial"};
var b = a;
a.num = 2;
console.log(b.num); // display 2
lastr2d2
  • 3,604
  • 2
  • 22
  • 37
0

There is only one case - parameters and function argument object - they magically change each other even when value is primitive type (this doesn't work in strict mode).

    function magicLink(a,b) {
        arguments[0] = 5;
        arguments[1] = 10;
        console.log([a,b]);
    }

    magicLink(1); // [5, undefined]

This only works for parameters set during invocation.

magyar1984
  • 186
  • 4