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
Post a Comment