Javascript 在不再需要变量时将变量设置为 null 是一种好习惯吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7189809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:16:17  来源:igfitidea点击:

Is it good practice to set variables to null when they are no longer needed?

javascriptnull

提问by bob

I have seen javascript values set to nullat the end of a function. Is this done to reduce memory usageor just to prevent accidental usageelsewhere?

我已经看到null在函数末尾设置了 javascript 值。这样做是为了减少内存使用还是只是为了防止其他地方的意外使用

Is there a good case for doing this. If so when?

是否有这样做的好案例。如果是什么时候?

var myValue;
.
.
.
myValue = null;

采纳答案by alex

It wouldn't make any difference setting a local variable to nullat the end of the function because it would be removed from the stack when it returns anyway.

null在函数的末尾设置一个局部变量没有任何区别,因为无论如何它都会从堆栈中移除。

However, inside of a closure, the variable will notbe deallocated.

但是,在闭包内部,变量不会被释放。

var fn = function() {

   var local = 0;

   return function() {
      console.log(++local);
   }

}

var returned = fn();

returned(); // 1
returned(); // 2

jsFiddle.

js小提琴

When the inner function is returned, the outer variable's scope will live on, accessible to the returned inner function.

当内部函数返回时,外部变量的作用域将继续存在,可被返回的内部函数访问。

回答by RobG

There was an issue with iE and circular references involving DOM elements. This was usually created when attaching listeners as follows:

涉及 DOM 元素的 iE 和循环引用存在问题。这通常是在附加侦听器时创建的,如下所示:

function doStuff() {
   var el = document.getElementById('someID');
   el.onclick = function() {
     // has closure to el
   };

   // remove reference to element
   el = null;
}

When doStuffia called, the anonymous function attached to the element has a closure back to the element - a circular reference. In older versions of IE this caused a memory leak so the solution was to set elto null(or anything other than el) to break the circular reference after the assignment to el.onclick.

doStuff被调用时,附加到元素上的匿名函数有一个返回到元素的闭包——一个循环引用。在旧版本的 IE 中,这会导致内存泄漏,因此解决方案是将el设置为null(或el以外的任何)以在分配给el.onclick.

The second reason to use it is similar - if a function has a closure that keeps a reference a large object that might otherwise be garbage collected, then it may be useful to remove the reference so that the object can be cleaned up:

使用它的第二个原因是类似的 - 如果一个函数有一个闭包,它保留一个大对象的引用,否则可能会被垃圾收集,那么删除引用以便可以清理对象可能很有用:

var someFunction = (function() {
  var x = reallyBigObject;
  // do stuff that uses reallyBigObject

  // Remove reference to reallyBigObject if it's no longer required
  x = null;

  return function() {
    // closure to x is unavoidable, but reference to reallyBigObject isn't required
  }
}());

So if the function returned to someFunctiondoesn't actually need to reference reallyBigObject, then the reference can be removed so the closure doesn't keep it from being garbage collected unnecessarily.

因此,如果返回到someFunction的函数实际上不需要引用realBigObject,那么可以删除该引用,这样闭包就不会阻止它被不必要地垃圾收集。

Note that you can't prevent the closure to variables in scope, but you can modify their values.

请注意,您无法阻止对作用域中的变量进行闭包,但您可以修改它们的值。

This stuff usually isn't much of an issue unless you are keeping pages open for a long time and doing lots of AJAX and adding and removing lots of DOM nodes. But it's probably a good habit to remove references to objects in closures where they aren't needed.

这些东西通常不是什么大问题,除非您长时间保持页面打开并执行大量 AJAX 并添加和删除大量 DOM 节点。但是在不需要它们的闭包中删除对对象的引用可能是一个好习惯。

回答by avall

No it isn't. Every local variable is deleted after the end of a function.

不,不是。每个局部变量在函数结束后都会被删除。

回答by webs

Yes very much so. Especially if the variable has some secret information such as a returned password.

是的,非常如此。特别是如果变量有一些秘密信息,例如返回的密码。

As soon as you use the variable declare it as null or "" because active variables in js can be read using inspect element.

一旦您使用该变量,就将其声明为 null 或 "",因为可以使用检查元素读取 js 中的活动变量。

var password = $('#password').val();

After evaluating variable password reset it to "". If you do not the value can be accessed by picking any of your existing html items such as a button and using inspect element to add the attribute code

评估变量密码后将其重置为“”。如果不这样做,则可以通过选择任何现有的 html 项目(例如按钮)并使用检查元素添加属性代码来访问该值

onclick = "javascript:alert(password);"

Resetting the variable password to null will keep your password information safe.

将变量 password 重置为 null 将确保您的密码信息安全。

var password = $('#password').val();
//do what you want to do with variable password
password = null;