Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

ecmascript 6 - reading / assigning reference types in JavaScript

I like to think I have and understanding of reference types, but I am wondering what I am missing here, what is happening under the hood.

let o = {
   foo: 'bar'
};

console.log(o) // logs the object.

let p = o; // assigns reference to object

I have seen this a thousand times and move on without a thought, but this time it gave me an unexpected psychedelic jolt.

In both cases my mind reads this as 'read the value of o and'. However, one will log the actual data stored whereas the other will return a reference. What step am I missing that makes these two lines differ?

  • is let p = o; how things normally work, but console.log(o) is causing some type of implicit / default call.

  • Or is it the inverse, that o will naturally pull the actual object from the heap but an assignment will by nature always assign the reference?

"when x JavaScript will z"

Can someone explain the workings of this so I understand the exact why of it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you copy the value, then you copy a reference to the object.

If you do anything else with it, then the reference is followed and the object worked with.


The value of o is a reference to an object.

If you assign o to p then you copy that reference and p is also a reference to the object.

If you access o.foo then you follow the reference to the object and do something with the foo property of it.

If you pass o to a function, then you copy the reference to the parameter in the function. If that function then accesses paramater.foo then it follows the reference to the object and does something with the value of foo on it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...