Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

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

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;
question from:https://stackoverflow.com/questions/7189809/is-it-good-practice-to-set-variables-to-null-when-they-are-no-longer-needed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

jsFiddle.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...