简体   繁体   中英

How do I read Javascript Closure Syntax?

Based on some code in a lecture by Doug Crockford, I've created this.

var isAlphaUser = (function() {
    alert("Forming Alpha User List");
    let AlphaUsers = {
        1234: true,
        5678: true
    };

    return function(id){
        alert("Checking Alpha Users:",id); 
        return AlphaUsers[id];};
}());

alert("starting");
alert(isAlphaUser(1234));
alert(isAlphaUser(5678));
alert(isAlphaUser(3456));

which gives me this:

Forming Alpha User List
starting
Checking Alpha Users: 1234
true
Checking Alpha Users: 5678
true
Checking Alpha Users: 3456
undefined

Which is quite cool, as it does the expensive setup once only, and every further call is a cheap check.

However, I can't decipher the code that does this. Specifically, I can't understand why I need the "()" at the end of the function declaration.

Can somebody explain how this syntax is working?

() calls a function. function() { } defines a function. Appending () right after immediately calls it 1 , and the result (also an anonymous function) is assigned to isAlphaUser .

The function() {... }() pattern is frequently used to isolate variables to an inner scope, so those variables don't become part of the global scope.

In this case, this is what happens:

  1. An anonymous function is run, defining a variable AlphaUsers inside that scope.
  2. That function returns another function that takes 1 parameter. This function is a closure to which the AlphaUsers variable becomes bound (in other words, available). This function checks if the parameter passed in is contained in AlphaUsers (actually, it returns the item at that index, which is just a boolean).
  3. The return value is assigned to a variable isAlphaUser .
  4. Since isAlphaUser is now a function, it can be called to see if the parameter is contained in the AlphaUsers variable, but no direct access to AlphaUsers is available in the global scope (it become a sort of private variable).

1 — Note : As cwolves mentioned in the comments, beware that while () appended directly after the } works in this case, it is only because in this case the function definition is a function expression . If function is the first word on the line, the line becomes a function declaration , and that is all that line can do, the function is not anonymous (it will require a name, otherwise it's a syntax error) and cannot be called immediately inline. See Function Declarations vs. Function Expressions for more info.

The () at the end of the code is separate from the closure issue. By wrapping your function in parens and adding the () at the end you are creating an anonymous function that is run immediately with whatever arguments you pass into ().

Specifically, I can't understand why I need the "()" at the end of the function declaration.

It creates self-invoking function, in other words, the function is executed as soon as it is parsed.

It is basically same thing when you call a function by suffixing it with () like:

myfunc();   // call this func

The top-level anonymous function returns the function that the isAlphasUser varaible refers to.

You need to call the top-level function, to get the inner-function reference.

Think of it like this, the outer anonymous function is a function factory, ie, it returns a function.

In order to use any function (even one that returns a function) you must call it.

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