简体   繁体   中英

JavaScript object behavior

I do not get stumped often but I am just at a loss of words right now.

Using Chrome 37.0.2062.120 m

Can someone explain to me why my console.log(); is reporting these results?

JS code

var some_obj = {min:1};

var another_obj = {};

console.log(some_obj);

another_obj['sometarget'] = some_obj; // <- What is this sorcery?!?!?
another_obj['sometarget']['required'] = true;

console.log(some_obj);

console.log() output

Object {min: 1}
Object {min: 1, required: true}

JSFIDDLE

http://jsfiddle.net/qrnaw7j2/1/

Objects in javascript are shared via reference.

So some_obj and another_obj['sometarget'] point to the same place in memory.

When you set ['required'] = true; in any of them, they will both get updated.

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