The function object in js is a fascinating thing, but because it is too flexible and often confusing, I will post some code below:
Most people have abbreviation like this:
How to write the entire book "Javascript Language Essence":
Functions can be run immediately and assigned values:
var test = function () {} () // test === undefined
var test2 = function () {return 'sugar cake'}() // test2 === 'sugar cake'
However, the abbreviation method of the function cannot be run directly, and the following code will report an error:
If you use the "()" run character to wrap it normally:
In fact, this function name test is meaningless anymore. If it is removed, it becomes an anonymous function. It can still automatically execute the code inside the function. Commonly used anonymous function writing methods:
Anonymous functions can also be written in this way, which may be a little more beautiful:
Seeing this, are you going crazy when you first came into contact with JS? I once saw my project in C language and petrified immediately after seeing anonymous functions...
Most people have abbreviation like this:
Copy the codeThe code is as follows:
function test () {}
How to write the entire book "Javascript Language Essence":
Copy the codeThe code is as follows:
var test = function () {}
Functions can be run immediately and assigned values:
Copy the codeThe code is as follows:
var test = function () {} () // test === undefined
var test2 = function () {return 'sugar cake'}() // test2 === 'sugar cake'
However, the abbreviation method of the function cannot be run directly, and the following code will report an error:
Copy the codeThe code is as follows:
function test() {}() // SyntaxError: syntax error
If you use the "()" run character to wrap it normally:
Copy the codeThe code is as follows:
(function test () {})();
In fact, this function name test is meaningless anymore. If it is removed, it becomes an anonymous function. It can still automatically execute the code inside the function. Commonly used anonymous function writing methods:
Copy the codeThe code is as follows:
(function () {})();
Anonymous functions can also be written in this way, which may be a little more beautiful:
Copy the codeThe code is as follows:
(function () {}());
Seeing this, are you going crazy when you first came into contact with JS? I once saw my project in C language and petrified immediately after seeing anonymous functions...