在JavaScript中读取/分配引用类型 [英] reading / assigning reference types in JavaScript

查看:61
本文介绍了在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

我已经看过1000遍了,不加思索地继续前进,但这一次给了我一个意想不到的迷幻震撼.

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

在两种情况下,我的头脑都将其读为"读取o和的值".但是,一个将记录实际存储的数据,而另一个将返回引用.我缺少哪一步使这两行不同?

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?

  • let p = o; 正常工作方式,但是 console.log(o)导致某种类型的隐式/默认调用.

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

或者相反, o 自然会拉出实际对象从堆中进行分配,但从本质上讲,分配将始终分配参考?

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?

"x JavaScript将在何时出现"

有人可以解释一下它的工作原理,以便我确切知道为什么吗?

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

推荐答案

如果您复制该值,则将对对象的引用复制.

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.

o 的值是对对象的引用.

The value of o is a reference to an object.

如果将 o 分配给 p ,则复制该引用,并且 p 也是对该对象的引用.

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

如果您访问 o.foo ,那么您将遵循对该对象的引用,并使用该对象的 foo 属性进行操作.

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

如果将 o 传递给函数,则将引用复制到函数中的参数.如果该函数随后访问 paramater.foo ,则它将遵循对该对象的引用,并对该对象执行带有 foo 值的操作.

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.

这篇关于在JavaScript中读取/分配引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆