gpt4 book ai didi

javascript - 在javascript中,下面的代码是如何工作的

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:03 25 4
gpt4 key购买 nike

在 Javascript 中,下面的代码是如何工作的。

var a = {
prop1: "a",
prop2: "b",
fun: function() {
return this.prop1 + " " + this.prop2;
}

}
var a2 = a;
a.fn = "v";
a = {};
if (a === a2) {
console.log(true);
} else {
console.log(false);
}

上面的代码打印错误。

但如果我注释掉 a={} 行,控制台上打印的值就是 true。

var a = {
prop1: "a",
prop2: "b",
fun: function() {
return this.prop1 + " " + this.prop2;
}

}
var a2 = a;
a.fn = "v";
//a={};
if (a === a2) {
console.log(true);
} else {
console.log(false);
}

上面的代码是如何工作的,因为两个变量(a 和 a2)都指向同一个对象,但是当我用 {} 初始化 a 时它给出了 false。

最佳答案

...as Both variables(a and a2) points to the same object ...

从这行开始,它们不再存在了:

a={};

此时,a2 指的是旧对象,a 指的是一个新的、不同的对象。

a2 = a 不会在变量 a2变量 之间创建任何类型的持续链接一个

让我们加入一些 Unicode 艺术:

这段代码运行后:

var a = {
prop1: "a",
prop2: "b",
fun: function() {
return this.prop1 + " " + this.prop2;
}

}
var a2 = a;
a.fn = "v";

此时,你的内存中有这样的东西(省略了各种细节):

a:Ref44512−−−+             |             |             |    +−−−−−−−−−−−−−+                              +−−−>|  (object)   |                              |    +−−−−−−−−−−−−−+                              |    | prop1: "a"  |                              |    | prop2: "b"  |   +−−−−−−−−−−−−+a2:Ref44512−−+    | fun:Ref7846 |−−>| (function) |                  | vn: "v"     |   +−−−−−−−−−−−−+                  +−−−−−−−−−−−−−+                 

Those "Ref" values are object references. (We never actually see their values, those values are just made up nonsense.) Notice that the value in a and the value in a2 is the same, however.

If you do a === a2 at this point, it will be true: Both variables refer to the same object.

But when you do this:

a={};
                  +−−−−−−−−−−−−−+a:Ref84521−−−−−−−>|  (object)   |                  +−−−−−−−−−−−−−+                  +−−−−−−−−−−−−−+                 a2:Ref44512−−−−−−>|  (object)   |                                   +−−−−−−−−−−−−−+                                   | prop1: "a"  |                                   | prop2: "b"  |   +−−−−−−−−−−−−+                  | fun:Ref7846 |−−>| (function) |                  | vn: "v"     |   +−−−−−−−−−−−−+                  +−−−−−−−−−−−−−+                 

此时,a === a2false:变量引用不同的对象。

关于javascript - 在javascript中,下面的代码是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com