I've been playing around with Node.js after having not used JavaScript for a long time.
One thing I've noticed is that many of the sample files I've been looking at use the following convention:
(function() {
... all javascript code for the file ...
})();
Is there a reason to enclose all the JavaScript in a file in a function like that, or is it just convention? Is it something I should mimic?
I should also note, that at least in the files I've been playing with, the code works the same way with or without the function surrounding everything.
Thanks for your insights!
In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.
The purpose of wrapping is to a namespace and control the visibility of member functions. It wraps the code inside a function scope and decreases clashing with other libraries.
Manipulation of file handling in JavaScript involves opening of file, closing of file, Updating data in file. JavaScript file handling does not get compiled by any compiler. It just needs an environment with a working browser where the translator can handle the java script code for the web browser.
Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the object's properties) with one or more methods.
Variables in Javascript have function scope. You're wrapping your code in a function in order for it not to clobber the global namespace with tons of variables, which may lead to bugs later on when different code is added. E.g.:
// module 1
(function () {
var foo = 'bar';
...
})();
// module 2
(function () {
var foo = 'baz';
...
})();
No problems, because both modules have their own variable scopes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With