Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript create reference to an object property?

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?

like image 498
Andrew Avatar asked May 12 '14 04:05

Andrew


1 Answers

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.

like image 65
fulvio Avatar answered Oct 17 '22 08:10

fulvio