Home  >  Article  >  Web Front-end  >  Several ways to write anonymous functions in JavaScript_javascript skills

Several ways to write anonymous functions in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:34:101138browse

Error mode: Syntax error warning

Copy code The code is as follows:

function(){
// insert code here
}();

Mode 1: Function Literal (Function Literal)

Declare the function object first and then execute it.
Copy code The code is as follows:

(function(){
// insert code here
})();

Mode 2: Priority Expression (Prior Expression)

Since JavaScript executes expressions in order from the inside to the outside, brackets are used to force execution of a declared function.
Copy code The code is as follows:

(function(){
// insert code here
}());

Mode 3: Void Operator (Void Operator)

Use Void operator to execute a single operand.
Copy code The code is as follows:

void function(){
// insert code here
}();

Technically, these three code patterns are equivalent. But in actual applications, such as YUI, jQuery and other frameworks, mode 1 is more widely used.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn