简体   繁体   English

设置对对象属性的引用

[英]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. 如果我有TheReference = TheObject那么那将允许我到达该特定对象,但是我正在寻找访问该对象的属性,以便我可以编写TheReference = "update"并在该对象的属性中更新该值。 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. 如果对象的属性本身是“ true”对象,则只能存储该对象的引用。 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. 我会用javascript质疑这样做的动机,但是也许您想隐藏原始对象并仅公开其属性之一。 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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