16

I understand that in javascript, primitives are passed by value and objects are passed by reference.

I'm interested in creating a workaround of some kind that would let me get a reference to an object property containing a primitive. For example, what I wish would work is:

var someObject = {a: 1, b: 2};
var myRef = someObject.b;
myRef ++;
someObject.b #=> 3

Of course, this doesn't work. I'm aware that you could create a getter and setter function instead, or use one object to reference another object, but what I'd really like is some kind of workaround that allowed me to define a variable as a reference to the property of another object, and so far it seems this just can't be done.

So, my question is simply: is this even possible, and if so, how?

Community
  • 1
  • 1
Andrew
  • 42,517
  • 51
  • 181
  • 281
  • 2
    The method you tried, will work only on mutable objects. – thefourtheye May 12 '14 at 04:34
  • So, I get that, and yet it seems like anything you've set as a property or a variable has at least that one reference pointing to it... so it seems like there should be some way to create a reference to the reference rather than a reference to the value... I suppose this isn't how JS works but at the moment it's not obvious to me why. – Andrew May 12 '14 at 04:38
  • You can only get a reference to an object or an array in javascript. So, the only way to get a reference to some other type is to put it inside an object or array and pass/assign the containing object or array. That's just how JS works. – jfriend00 May 12 '14 at 04:40
  • 2
    There's probably no good way to do that, and even if there is a workaround you probably shouldn't be using it, as it sorta defeats the point of passing by "copy-reference" (javascript does **not** pass by reference). – adeneo May 12 '14 at 04:44
  • @Andrew You are incrementing a number, which is immutable. So, after incrementing, a new immutable object of the incremented value will be created and the reference `myRef` will refer that newly created object. So, anyway you will lose the old reference. – thefourtheye May 12 '14 at 04:56
  • **See also:** https://stackoverflow.com/q/7744611/1599699 Basically the same underlying question/problem. – Andrew Mar 24 '23 at 12:28

4 Answers4

7

Primitive types are immutable, so no, it's not possible. You can wrap your primitive type with an object, like this:

function MyNumber(n) { this.n = n; }
MyNumber.prototype.valueOf = function() { return this.n; }
var someObject = { a: 1, b: new MyNumber(2) };
var myRef = someObject.b;
MyNumber.call(myRef, myRef + 1);
console.log(+someObject.b); // convert to number with +

OR

var someObject = {
    a: { value: 1 },
    b: { value: 2 },
};
var myRef = someObject.b;
my_inc(myRef); // function my_inc (obj) { obj.value++; }
// someObject.b.value == 3

The React framework uses a very simple pattern to encapsulate values.

function Link(value, requestChange)
{
    this.value = value;
    this.requestChange = requestChange;
}

You can pass around the object, the current value can be accessed by inspecting the value property of the object, if you want to change it you can call requestChange with a new value, you can change the value. The advantage would be to have the actual "storage location" and the logic for changing the value decoupled from the value read and write access. Note that the values can also be complex objects.

You could also achieve something similar with closures:

var someObject = {
    a: 1,
    b: 2
};

function property(object, prop) {
    return {
        get value () {
            return object[prop]
        },
        set value (val) {
            object[prop] = val;
        }
    };
}

var ref = property(someObject, "b");
ref.value; // 2
++ref.value; // 3
someObject.b; // 3

This works because the getter and setter functions have access to whatever bindings were in scope at the time of their creation (object and prop). You can now pass ref around, store it in a data structure, etc.

gotnull
  • 26,454
  • 22
  • 137
  • 203
0

No, there isn't a nice way to do it.

You can use a work-around if you want to. Something like wrapping all your primary data types with single element arrays:

var someObject = {a: [1], b: [2]};
var myRef = someObject.b;
myRef[0]++;
someObject.b[0]; // 3

That's less than ideal though, as you have to use [0] to access the property all the time. There are some cases where it can be useful though, and the default toString of a single element array is just the toString of its element, so you can use the property directly in a string context:

console.log('My value: ' + someObject.b); // 'My value: 3'
Paul
  • 139,544
  • 27
  • 275
  • 264
  • There kind of are nice ways to do it though. For one, you could simply store the `someObject` as the reference and then use `someObjectRef.b`; that's not bad. Another nice way might be to create functions (or, if necessary, function factories, using the [Factory pattern](https://en.wikipedia.org/wiki/Factory_method_pattern)) if you need to do more complex or redundant operations with references. – Andrew Mar 24 '23 at 12:24
  • Lastly, if your primary goal is to avoid lots of syntax (a "nice" way), you might consider using a [`Proxy`](https://stackoverflow.com/a/7891968/1599699) or [`Object.defineProperty()`](https://stackoverflow.com/a/62727149/1599699) (potentially using getters, setters, and/or [`apply`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply) (for the `object.property()` syntax)). – Andrew Mar 24 '23 at 12:24
0

I don't know how satisfying this is, but you could do it if you were ok with wrapping the desired object in an object like so:

var a = {a:{a:1},b:2};
var b = a.a;
b.a++;
a.a.a //=> 2

It isn't exactly what you asked for, but it would work.

Mobius
  • 2,871
  • 1
  • 19
  • 29
  • 1
    Using that logic you could just do `someObject.b++`, but that wasn't the point – adeneo May 12 '14 at 04:41
  • I guess I was thinking you could use it in function pointers like in @gotnull's answer. so fptr(a.a) could then change your a.a.a if you wanted. – Mobius May 12 '14 at 14:01
  • @adeneo It kind of is the point, or can be. This approach and similar approaches actually address the problem quite well; see my comments above. – Andrew Mar 24 '23 at 12:28
0

if you want to "link" or "synchronize" two properties , each of a different object, you could do it like this:

var someObject = {
    a: 1,
    b: 2
};
var linkedObject = {
    a:1, 
    b:2
}
function property(object, prop) {
    return {
        get value () {
            return object[prop]
        },
        set value (val) {
            object[prop] = val;
        }
    };
}
var s_prop = 'b'
var o_ref = property(someObject, s_prop);
var tmp = linkedObject[s_prop]; 

Object.defineProperty(
    linkedObject,
    s_prop,
    {

        set: function(value) {
            o_ref.value = value;
        },
        get: function() {
            return o_ref.value
        }
    }
);
linkedObject[s_prop] = tmp 

someObject.b = 333 /// linkedObject.b is also 333 now
console.log(someObject.b) //  333 
console.log(linkedObject.b)// 333

linkedObject.b = {"test": 2}
console.log(someObject.b) //  {test:2}
console.log(linkedObject.b)// {test:2}

someObject.b.test = 3 
console.log(someObject.b) // {test:3}
console.log(linkedObject.b)//{test:3}
Jonas Frey
  • 65
  • 6
  • In the vast majority of cases, it would be better to simply re-use the object containing the shared properties, as a [Flyweight object](https://en.wikipedia.org/wiki/Flyweight_pattern), i.e. set the object as a property of other variables/objects. That way you don't need to do any getter/setter type stuff. There are of course more complex problems where that sort of code might be required, but the simpler Flyweight pattern is preferable otherwise. – Andrew Mar 24 '23 at 12:17