2

Is there a way to pass an object property to a function by reference instead of by value?

ES5 properties can have getters and setters. How to pass a variable that uses the getters and setters instead of the result of the getter?

Right now I have to pass a reference to the whole object, not just the single property I want.

Manuel
  • 10,869
  • 14
  • 55
  • 86

4 Answers4

0

Is there a way to pass an object property to a function by reference instead of by value?

No. In fact it doesn't ultimately make a lot of sense to "pass an object property", as the notion of a "property" doesn't exist without the entity that it is a property of.

If this is simply a matter of encapsulation and not wanting to leak full control, you can always get creative. E.g.,

var obj = {
    sensitive: 'do not share me!',
    public: 'hi there',
    setPublic: function(val) {
        this.public = val;
    }
};

function someFunction(setter) {
    setter('new value');
}

someFunction(obj.setPublic.bind(obj));
jmar777
  • 38,796
  • 11
  • 66
  • 64
0

There's no way to do exactly what you're asking because no matter what it's source, value types (i.e. non-objects/arrays) will be passed by value. However, if you create a get/set function, you could pass the function bound to the object.

var obj = {
  _val: 0,
  val: function(x) {
    if (x !== undefined) {
      this._val = x;
    } else {
      return this._val;
    }
  }
}

function doStuff(prop) {
  if (prop() > 1) {
    prop(0);
  }
}

doStuff(obj.val.bind(obj));
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

You could always pass two arguments, the object and the property name:

function change(obj, prop, newVal) {
  obj[prop] = newVal;
}

var obj = { foo: 1 };

change(obj, 'foo', 99);
console.log(obj); // => { foo: 99 }
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
0

The short answer is no because, as you have already mentioned in your question, primitive types are passed by value.

There is an interesting SO answer which explains it in details and also links to a very detailed blog post.

However if you really do need to do so, you can create a wrapper object for the specific property you are trying to pass around, however this is a workaround more than a solution.

Community
  • 1
  • 1
Michele Ricciardi
  • 2,107
  • 14
  • 17