在javascript中对象引用未定义 [英] Object references to undefined in javascript

查看:116
本文介绍了在javascript中对象引用未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个javascript中的对象并且它引用了另一个对象,然后第二个对象发生了变化,你可以期待看到引用对象的变化。但是,如果第二个对象最初未定义,则第一个对象将永远不会反映新的更改。任何人都可以解释这段代码中发生的事情吗?

If you have an object in javascript and it references another object and then 2nd object changes, you can expect to see the change in the referenced object. However, if the 2nd object is initially undefined, the first object will never reflect new changes. Can anyone potentially explain what is happening under the hood in this code?

//Here we see the reference updated
var myobj = {};
var pointer = myobj;
myobj.value = 1;
console.log(pointer.value);

//Here if we start as undefined, create a reference and then allocate a new object - not so much    
var myobj = undefined;
var pointer = myobj;
myobj = {}
myobj.value = 1;
console.log(pointer.value);

这是在

$ node --version 
v0.8.22


推荐答案

答案很简单。您需要了解值和引用类型变量之间的区别。

The answer is pretty simple. You need to understand the difference between a value and reference type variables.

在第一个例子中有一个引用类型变量,即 myObj ,它指向内存中的一个区域。然后定义一个指向同一区域的另一个变量,即指针。这就是为什么对一个对象的任何更改立即反映在另一个对象上的原因。

In the first example have a reference type variable i.e. myObj which points to an area in the memory. Then you define one more variable i.e. pointer that points to the same area. That's why any changes to one object is instantly reflected on the other.

在第二个例子中,情况略有不同。您定义了 myObj ,它是未定义类型。这意味着没有为此变量指定值。如果你有一个值类型变量,你会这样做,例如您没有要分配值的数字,字符串等;这也意味着 myObj 并未指向内存堆部分中的任何内容。
然后当你这样做时var pointer = myobj;你只是将一个变量的值复制到另一个变量;它类似于这样做,例如:var pointer = 5;这称为按值复制,这就是未反映更改的原因。

In the second example things are slightly different. You define the myObj which is of Undefined type. Which means that there is no value specified for this variable. You would do that in the case where you have a value type variable e.g. Number, string etc. for which you don't have a value to assign; It also means that myObj doesn't point to any are in the heap section of the memory. Then when you do this var pointer = myobj; you're simply copying the value of one variable to the other; It's similar to doing this, for example: var pointer = 5; This is called copy by value' so that's why the changes are not reflected.

这篇关于在javascript中对象引用未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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