Does javascript create a reference to an object property?

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

I am interested in creating a workaround that would allow me to get a reference to an object property containing the primitive. For example, I would like to:

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

Of course, this does not work. I know that instead you can create a getter and setter function or use one object to reference another object, but what I really like is some kind of workaround that allowed me to define a variable as a property reference to another object, and so far it seems that this is simply impossible.

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

+4
source share
3 answers

Primitive types are immutable, so no, this is not possible. You can transfer your primitive type to an object, for example:

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 template to encapsulate values.

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

You can bypass the object, the current value can be accessed by checking the value of the property of the object, if you want to change it, you can call requestChangewith a new value, you can change the value. The advantage would be to have an actual “storage location” and logic for changing the value separate from access to read and write values. Note that values ​​can also be complex objects.

You can also achieve something similar with closure:

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

, getter setter , (object prop). ref, ..

+2

, .

, . - :

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

, [0] . , , toString - toString , :

console.log('My value: ' + someObject.b); // 'My value: 3'
0

, , , :

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

, , .

-1
source

Source: https://habr.com/ru/post/1540161/


All Articles