简体   繁体   中英

Javascript Anonymous Closure

I have read a lot about closures in Javascript What are those braces for?? I read on mozilla.org which says closure should be defined as

(function(){...})();

but on http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html , it says the closure function is

(function(){...}());

What's the difference or the latter one is wrong? what's the purpose of the last ()? Would you put some parameters inside? I am looking for a good reference.

Edit: Moreover, there is an example on Mozilla.org

var makeCounter = function() {
var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }  
};

why the semicolon is needed for this 'function'? If it needs to be invoked immediately after its declaration, a () should be put before the ending semicolon. But there is not.

The syntax

(function(){...})()

is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked.

Closures are instead used to describe a situation where a function has access to variables declared outside of its scope, accessible via closures

For clarity :

If we have the following function

   function hello() {
      alert("Hello");
   }

We can call the function with the following

hello()

Which invokes the function 'hello'. But if we do not wish to give it a name, but still invoke it, then we can do

(function hello() {
   alert("Hello");
})()

Which will do the exact same as the previous example of calling hello

However, in this scenario there is no point in giving the function the name 'hello', so we can simply remove it:

(function() {
    alert("Hello");
})()

Which is the notation used in your original question.

Your example shows an Immediately Invoked Function Expression , or IIFE. It says to the interpreter:

  • here is a function
  • it has no name
  • keep it away from the global scope ie 'window'
  • call it now

Yes, you can put parameters inside the last (). For example:

(
    function(username){
        alert("Hello " + username);
    }
)("John Smith")

Closures are a feature of javascript that allows us to implement data hiding which is roughly equivalent to private variables in languages like C++ or Java.

function getBmiCalculator(height, weight) {
    // These are private vars
    var height = height;
    var weight = weight;

    function calculateBmi(){
        return weight / (height * height);
    }
    return calculateBmi;
}

var calc = getBmiCalculator(1.85, 90);

// calc still has access to the scope where height and weight live.
var bmi = calc();
alert(bmi);

In this example, height & weight cannot be garbage-collected until calc is destroyed. The section of memory or "scope" where height & weight exist are "Closed Over"

There is no difference. You can also do so:

true && function(){ /* code */ }();
0,function(){ /* code */ }();

!function(){ /* code */ }(); // Facebook style
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();

// with new    
new function(){ /* code */ }
new function(){ /* code */ }() // if you need arguments then use brackets

the grouping operator can surround the function description as without call parentheses, and also including call parentheses. Ie both expressions below are correct FE:

      (function () {})();
      (function () {}());

Function Expression

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM