设置对象属性的引用

时间:2015-10-29 15:18:27

标签: javascript

我有一个对象数组,我想设置和重置对这些对象之一的属性的引用。假设我有以下内容:

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

我的目标是存储对象属性的引用,然后通过访问引用来更新该属性。如果我有TheReference = TheObject那么这将允许我到达该特定对象,但我想要访问该对象的属性,以便我可以编写TheReference = "update"并且该值在对象&中更新#39; s属性。什么是存储对象属性的引用的方法?

2 个答案:

答案 0 :(得分:0)

如果该属性本身是“true”对象,则只能存储对象属性的引用。您上面的代码无法正常工作,因为您正在尝试引用字符串,但这将:

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'

答案 1 :(得分:0)

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"