gpt4 book ai didi

javascript - 为什么这个变量还活着?

转载 作者:搜寻专家 更新时间:2023-11-01 05:07:09 25 4
gpt4 key购买 nike

我有以下源代码。

testObj = {}

function testFun()
{
this.name = "hi";
}

function test () {

var instanceOfTestFun = new testFun();

testObj.pointerToFun = instanceOfTestFun;

instanceOfTestFun = null;

console.log(testObj);

}

$(document).ready(test);

我希望看到 testObj 的控制台输出为“null”,但我看到了 testFun 函数。我认为 javascript 对对象使用“通过引用传递”。

请...建议我...

最佳答案

testObj.pointerToFuninstanceOfTestFun 是对同一对象的两个引用。

当您编写 instanceOfTestFun = null 时,您正在将 instanceOfTestFun 更改为指向任何内容。
这不会影响 testObj.pointerToFun,它仍然引用原始对象。

如果您更改原始对象(例如,instanceOfTestFun.name = "bye"),您将通过两个访问器看到更改,因为它们都指向(现在已更改的)对象。

关于javascript - 为什么这个变量还活着?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8335220/

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