简体   繁体   中英

Setting a reference to a property of an object

I have an array of objects and I want to set and reset a reference to a property of one of these objects. Suppose I have the following:

var TheReference = null;
var TheArrayOfObjects = [];
var TheObject = {};

TheObject.SomeProp1 = "test1";
TheObject.SomeProp2 = "test2";

TheArrayOfObjects.push(TheObject); // this array could contain hundreds of objects

TheReference = TheObject.SomeProp1; // here I know it's not a reference.
TheReference = "update"; // so of course it doesn't update the object's property

My goal is to store a reference to an object's property and then update that property by accessing the reference. If I had TheReference = TheObject then that would allow me to reach that particular object but I'm looking to access a property of that object so that I can write TheReference = "update" and that value is updated in the object's property. What's a way to store a reference to an object's property?

You can only store a reference to an object's property if that property itself is a "true" object. Your code above won't work as you're asking because you're trying to reference a string, but this will:

var TheReference = null;
var TheArrayOfObjects = [];
var TheObject = {};

TheObject.SomeProp1 = {p1: "test1", p2: "test2"};
TheObject.SomeProp2 = {p3: "test3", p4: "test4"};

TheArrayOfObjects.push(TheObject); // this array could contain hundreds of objects

TheReference = TheObject.SomeProp1; // here I know it's not a reference.
alert(TheReference.p1); // will show 'test1'

I would question the motivation for this in javascript, but perhaps you want to hide the original object and expose only one of it's properties. You could create a closure which updates your object's property, but does not expose the original object:

function update(obj, prop, val) {
  if(!val) return obj[prop];
  obj[prop] = val;
}

var theRef = null,
    theArr = [],
    theObj = {
      one: 'test one',
      two: 'test two'
    },
    refToPropOne;

theArr.push(theObj);

refToPropOne = update.bind(null, theObj, 'one');
console.log(theArr);  // [{one: "test one", two: "test two"}]

refToPropOne('new val');
console.log(theArr); // [{one: "new val", two: "test two"}]

refToPropOne('replaced');
console.log(theArr);  // [{one: "replaced", two: "test two"}]

console.log(refToPropOne()); // "replaced"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM