最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

variables - Javascript create reference to an object property? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited May 23, 2017 at 11:53 CommunityBot 11 silver badge asked May 12, 2014 at 4:27 AndrewAndrew 43.1k53 gold badges183 silver badges285 bronze badges 6
  • 2 The method you tried, will work only on mutable objects. – thefourtheye Commented May 12, 2014 at 4: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 Commented May 12, 2014 at 4: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 Commented May 12, 2014 at 4: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 Commented May 12, 2014 at 4: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 Commented May 12, 2014 at 4:56
 |  Show 1 more comment

4 Answers 4

Reset to default 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.

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}

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'

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.

发布评论

评论列表(0)

  1. 暂无评论