JavaScript – 一个自我调用的匿名函数是否足以保护全局名称空间的variables?

这个代码能用闭包写得更好吗? 有没有更好的方法来写它,或者function保护variables?

(function(){ var http = require('http'), port = process.argv[2], string = "", length = 0; http.get(port, function(res){ res.on('data', function(data){ length += data.length; string += data; }); res.on('end', function(){ console.log(length); console.log(string) }); }); })(); 

这确实将variables保持在自己的范围之内,并且不能被任何外部代码使用:

 (function() { var so = '//stackoverflow.com'; alert(so); will alert '//stackoverflow.com' })(); alert(so); // Will alert Undefined **See note at bottom 

看看他的post,我发现一个快速的谷歌search

注意:如下面的注释中所述,这不会提醒未定义,但实际上会抛出一个引用错误,因为在IIFE之外的范围中不存在引用错误。 看看更多的MDN !