Why enclose javascript file in a function?
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 surrou开发者_如何转开发nding everything.
Thanks for your insights!
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.
Maybe its better to refer you to some good resources
related topic in stackoverflow
What are the benefits of a closure, and when are they typically used?
some detail explaination
http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
or more:
search result from stackoverflow
https://stackoverflow.com/search?q=javascript+closure
recently given answer on the same. This is an anonymous function which will execute its body.
So when the file containing this code loads all the logic inside this function is self executed.
(function() {
alert('hi');
})();
try writing this and executing. Also you can have your variables inside the scope of this function so that they do not interefere with a global scope and bring up errors when used with other javascript libraries.
It creates a scope, so it is useful for information hiding and not polluting the global object.
精彩评论