node.js - JavaScript - Does a self-invoking anonymous function protect variables against the global namespace sufficiently? -


would code better written using closure? there better way write it, or function protect 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)         });     });  })(); 

this keep variables within , out of reach external code:

(function() {   var = '//stackoverflow.com';    alert(so); alert '//stackoverflow.com' })();  alert(so); // alert undefined **see note @ bottom 

take @ post found quick google search

note: stated in comment below, not alert undefined, throw reference error, since so non existent in scope outside of iife. take @ mdn more!


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -