admin管理员组

文章数量:1289541

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?

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?

Share Improve this question asked Jul 14, 2011 at 17:10 dewordedeworde 2,7996 gold badges34 silver badges63 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 13

() calls a function. function() { } defines a function. Appending () right after immediately calls it1, 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 bee 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 bees 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 bee a sort of private variable).

1 — Note: As cwolves mentioned in the ments, 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 bees 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, i.e., it returns a function.

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

本文标签: How do I read Javascript Closure SyntaxStack Overflow