I often write code like this in the <script> of TPL:
$ (function() { alert ("I am so Hungry");});
At the beginning of the time only know that it does not need to call, direct execution, so according to gourd painting scoop, I wrote a lot of code. Said this, but also to say that the load order of the goods, if the code is written directly into the script tag, when the page loaded the script tag will execute the inside code. If you use the non-loaded DOM in this code or call a method that is not loaded, you will get an error. In fact, this function is actually self-executing function, many people will be more professionally referred to as "immediately called function expression."
Here, I quote the next Limlimlim blog, feel more professional ... Site http://blog.csdn.net/limlimlim/article/details/9198111
When you declare something like function foo () {} or var foo = functions () {}, you can implement self-execution by appending parentheses to it, such as Foo (), and see the code:
// because you want the function of the first declaration below to be appended with a parenthesis () You can do it yourself, such as Foo (), // because Foo is just function () { /* Code */} A reference to this expression var foo = function () {/* code */ } // ... Does that mean that the parentheses can be executed automatically after the next one? function () {/* code */} (); // syntaxerror:unexpected token ( //
The code above, if even run, the 2nd code error, because when the parser resolves the global function or function internal function keyword, the default is to think of the function declaration, rather than the function expression, if you do not display tell the compiler, It is declared as a function with a missing name by default, and throws a syntax error message because a function declaration requires a name.
Interestingly, even if you add a name to the wrong code above, he will also prompt for grammatical errors, except for the reasons above. After an expression with parentheses (), the expression executes immediately, but after a statement with parentheses (), it is completely different, and his only grouping operator.
//The following function is syntactically fine, but it's still just a statement//parentheses () will still cause an error, because the grouping operator needs to include an expression functionFoo () {/*Code*/}();//syntaxerror:unexpected token) //But if you pass an expression in parentheses (), there will be no exception thrown//but the Foo function will still not executefunctionFoo () {/*Code*/} (1 ); //because it is completely equivalent to the following code, a function declaration followed by a declaration of an unrelated expression:functionFoo () {/*Code*/ } ( 1);
To solve the problem, it's very simple, we just need to enclose the code in parentheses, because the parentheses () in JavaScript cannot contain statements, so at this point, when the parser parses the function keyword, The corresponding code is parsed into a function expression, not a function declaration.
//The following 2 brackets () will be executed immediately(function() {/*Code*/} ());//recommended use of this(function() {/*Code*/})();//but this can be used, too.//due to the && of brackets () and JS, the XOR, comma, and other operators are ambiguous on function expressions and function declarations .//so once the parser knows that one of them is already an expression, the others are the expressions by default.//However, please note that the following section explainsvari =function() {return10; } ();true&&function() {/*Code*/ } ();0,function() {/*Code*/ } ();//If you don't care about the return value, or are not afraid to read//you can even add a unary action symbol in front of the function!function() {/*Code*/ } ();~function() {/*Code*/ } ();-function() {/*Code*/ } ();+function() {/*Code*/ } ();//In another case, using the New keyword can also be used, but I'm not sure how efficient it is//http://twitter.com/kuvos/status/18209252090847232New function() {/*Code*/ }New function() {/*Code*/} ()//If you need to pass parameters, just add parentheses ()
The above-mentioned parenthesis is to eliminate ambiguity, in fact, there is no need, because the parentheses originally expected is the function expression, but we still use it, mainly for the convenience of developers to read, when you let these automatically executed expressions assigned to a variable, we see the beginning of the parentheses (, soon to understand Instead of pulling the code to the end to see if there are any parentheses.
In this post, we have been called self-executing functions, specifically self-executing anonymous functions (self-executing anonymous function), but the English original author has always advocated the use of immediately called function expressions (immediately-invoked Function Expression) This name, the author also gave a bunch of examples to explain, OK, let's take a look:
//This is a self-executing function that executes itself within the function, recursivelyfunctionfoo () {foo ();}//This is a self-executing anonymous function because no name is indicated//You must use the Arguments.callee property to perform your ownvarFoo =function() {Arguments.callee ();};//This may also be a self-executing anonymous function, only the Foo flag name refers to itself//If you change foo to something else, you'll get a used-to-self-execute anonymous functionvarFoo =function() {foo ();};//Some people call this a self-executing anonymous function (even if it's not), because it doesn't call itself, it just executes immediately. (function() {/*Code*/ } ());//add an indication name to the function expression to facilitate debug//but it must be named, and the function is no longer anonymous.(functionFoo () {/*Code*/ } ());//immediately called function expressions (Iife) can also be self-executing, but may not be commonly used(function() {Arguments.callee ();} ());(functionfoo () {foo ();} ());//In addition, the following code executes in BlackBerry 5 with an error, because in a named function expression, his name is undefined//Oh, strange(functionFoo () {foo ();} ());
Hopefully here are some examples that can make you understand what is called self-executing and what is called immediate invocation. (I have come here to understand a little, long live the theory)
The following Limlimlim also talked about the module mode , which is the important thing I will learn later, of course, before this there are closures (head Large)
Let me show you an example.
//Create an anonymous function expression that is called immediately//return a variable in which the variable contains what you want to expose//The returned variable will be assigned to counter, not the function itself declared outside.varCounter = (function () { vari = 0; return{get:function () { returni; }, set:function(val) {i=Val; }, Increment:function () { return++i; } };} ());//counter is an object with multiple attributes, and the above code is actually a way of representing the property.counter.get ();//0Counter.set (3); Counter.increment (); //4Counter.increment ();//5counter.i;//undefined because I is not a property of the returned objectI//Reference Error: I is not defined (because I only exist in closures)
Learning JS Function--Self-executing function