Home > Web Front-end > JS Tutorial > body text

Add operator before analyzing function to execute function immediately

高洛峰
Release: 2017-03-12 13:09:14
Original
1338 people have browsed it

We know that the function is usually called by FunctionName()

But if we try to add () to the end of a "define function", the parser is incomprehensible.

function msg(){
  alert('message');
  }();//解析器是无法理解的
Copy after login

The calling method of the defined function should be msg().

If you want the function to be executed immediately, you can wrap the function body with ().

This is because if you use parentheses to wrap the defined function body, the parser will call the defined function in the form of function expression. In other words, any method that can turn a function into a function expression can enable the parser to correctly call the defined function. As follows:

// 这么写会报错,因为这是一个函数定义:
function() {}()

// 常见的(多了一对括号),调用匿名函数:
(function() {})()

// 但在前面加上一个布尔运算符(只多了一个感叹号),就是表达式了,将执行后面的代码,也就合法实现调用
!function() {}()
Copy after login

! is just one of the operators, and + - || ~ all have such functions.

Using ! may be more of a matter of habit. Different operators have different performances.

The effect is equivalent to the following two commonly used immediate execution methods:

(function() {})();
  // or  
(function() {}());
Copy after login

Thank you for reading.

The above is the detailed content of Add operator before analyzing function to execute function immediately. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template