当不再需要变量时将变量设置为 null 是一种好习惯吗? [英] Is it good practice to set variables to null when they are no longer needed?
问题描述
我已经看到在函数的末尾将 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 是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!