问题描述
我在功能结束时看到javascript值设置为 null
。
这样做是为了减少内存使用量还是仅仅防止意外使用在其他地方?
I have seen javascript values set to null
at the end of a function.Is this done to reduce memory usage or just to prevent accidental usage elsewhere?
是否有这样做的好例子。如果是这样的话?
Is there a good case for doing this. If so when?
var myValue;
.
.
.
myValue = null;
推荐答案
设置局部变量没有任何区别函数结束时 null
,因为无论如何它都将从堆栈中删除。
It wouldn't make any difference setting a local variable to null
at the end of the function because it would be removed from the stack when it returns anyway.
但是在闭包内部,变量将不被释放。
However, inside of a closure, the variable will not be deallocated.
var fn = function() {
var local = 0;
return function() {
console.log(++local);
}
}
var returned = fn();
returned(); // 1
returned(); // 2
。
当返回内部函数时,外部变量的作用域将继续存在,可以被返回的内部函数访问。
When the inner function is returned, the outer variable's scope will live on, accessible to the returned inner function.
这篇关于在不再需要变量时将变量设置为null是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!