angularJsNewbie
angularJsNewbie

Reputation: 495

Javascript: two references to the same primitive, changing at the same time?

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?

Upvotes: 2

Views: 130

Answers (2)

magyar1984
magyar1984

Reputation: 186

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.

Upvotes: 0

lastr2d2
lastr2d2

Reputation: 3968

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

Upvotes: 2

Related Questions