作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有以下源代码。
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.pointerToFun
和 instanceOfTestFun
是对同一对象的两个引用。
当您编写 instanceOfTestFun = null
时,您正在将 instanceOfTestFun
更改为指向任何内容。
这不会影响 testObj.pointerToFun
,它仍然引用原始对象。
如果您更改原始对象(例如,instanceOfTestFun.name = "bye"
),您将通过两个访问器看到更改,因为它们都指向(现在已更改的)对象。
关于javascript - 为什么这个变量还活着?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8335220/
我是一名优秀的程序员,十分优秀!