Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  187] [ 7]  / answers: 1 / hits: 43213  / 14 Years ago, sun, august 29, 2010, 12:00:00

A long time ago, I saw someone encapsulate their entire JavaScript block with code something like the code below:



(function() {
// ...
})(this);


Questions:




  1. Is the code above correct?

  2. What benefit is there to encapsulating the entire JavaScript block like denoted above?


More From » javascript

 Answers
172

Yes, that's correct. It's called a self invoking anonymous function expression.



JavaScript variables have either function scope, or global scope. There is no block scope. Enclosing your code in a self invoking function like the one in your example creates a temporary local scope for single-use, immediately-run code, without polluting the global namespace.



Consider the following:



<html>
<body>
...
<script>
(function() {
var x = '';

function myFunction () {
alert('Hello: ' + x);
}

x = 'Bob';
myFunction();

alert(typeof x); // string
alert(typeof myFunction); // function
})();

alert(typeof x); // undefined
alert(typeof myFunction); // undefined
</script>
<script src=other-javascript.js></script>
</body>
</html>


Whatever you declare in that self invoking function is held in a separate scope. The variable x and the function myFunction() cannot be accessed from anywhere else. The code in other-javascript.js won't see them, for example, and it would be free to declare another function myFunction() without conflicts.


[#95763] Thursday, August 26, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carlo

Total Points: 705
Total Questions: 87
Total Answers: 101

Location: Indonesia
Member since Wed, Jul 7, 2021
3 Years ago
;