The way the js function is called

  • 2020-03-30 02:50:51
  • OfStack

There are several cases of Js function call:

(1) the named function is directly called


function foo()
  {
  }
  foo();

(2) anonymous functions are called by reference


  fooRef = function()
  {
  }
fooRef();

(3) anonymous function call 1 without reference


(function()
 {
}());

(4) anonymous function call 2 without reference


 (function()
 {
 })();
 

  (5) anonymous function call 3 without reference
 


 void function()
 {

 }();


< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/20140506104516.jpg? 201446104553 ">

Figure 1.1 and figure 1.2 shows the process of the two kinds of expression is different, is to use force in figure 1.1 the operator to perform the function call operation, use force in figure 1.2 the operator operation "function directly quantity statement" this expression, and retrieves a reference to a function itself, and then through the function call operation "()" to manipulate the function reference. The last anonymous function above calls void function(){}(); Is used to call a function and ignore the return value, and the operator void is used to make the function expression following it perform an operation. If we do not use "void" and forced operation "()", can the code execute:

(1)function(){}()//

(2) the function () {} (); / / the use of ";" To execute the statement

The script engine will think that function(){} is a function declaration, so it will not pass the syntax detection. The code will be parsed as follows:

The function () {}; (a);

Function (){} is interpreted as a declaration, while "();" It is explained in a single line, so it makes grammatical errors. Why do you know it is "();"? The resulting error? We change it to the following code:

The function () {} (1);

This will be interpreted by the engine as:

Fucntion () {};

(1); // single-valued expression

Thus passed the syntax check...


Related articles: