简体   繁体   中英

Javascript combine two objects keeping references

A simple example of what I'd like to do:

data = {name: 'fred'};

newData = {};
newData.name = data.name;

newData.name = 'ted';

console.log(data.name); // I want this to be ted not fred

Is it possible in Javascript to edit the second object and have it modify the first? I'm using alloyui 1.5 (yui 3.4.0) and trying to merge objects to create a datatable so the data appears on a single row but it needs to be editable, so it needs to point back to the original object.

Is such a thing possible or will I need to use events to push the data back to the first object?

You can do this if property of your objects is also an object. This works:

data = {name: {first:'fred'}};

newData = {};
newData.name = data.name;

newData.name.first = 'ted';

console.log(data.name.first) // outputs ted

yes, you can make a new object reference of the first( your data object) as newData using javascripts Object(). Changing either objects property reflects to the other .

data = {name: 'fred'};

var newData = new Object(data);

newData.name = 'ted';

console.log(data.name);// outputs ted

you can read more about Object() here

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