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

Problems with adding ! in front of function in js, the code is attached

亚连
Release: 2018-05-18 10:18:22
Original
1329 people have browsed it

The following are the questions I have compiled for you about adding ! in front of function in js. Interested students can take a look.

We all know that there are two ways to declare a function

function fnA(){alert('msg');}//声明式定义函数
var fnB = function(){alert('msg');}//函数赋值表达式定义函数12
Copy after login

The calling method of a function is usually FunctionName()

However, if we Try adding () to the end of a "define function", the parser will not understand it.

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

The calling method of defining a function should be msg(); Then why is it enough to wrap the function body with ()?

It turns out that if you use parentheses to wrap the function body, the parser will call the defined function in the form of a 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. And ! is one of them, and - || ~ has such a function.

In addition, using ! may be more of a matter of habit. Different operators have different performances.

// 这么写会报错,因为这是一个函数定义:
function() {}()
// 常见的(多了一对括号),调用匿名函数:
(function() {})()
// 但在前面加上一个布尔运算符(只多了一个感叹号),就是表达式了,将执行后面的代码,也就合法实现调用
!function() {}()
Copy after login

The above are the questions I compiled for you about adding ! in front of function in js. I hope it will be helpful to you in the future.

Related articles:

Detailed explanation of how JS interacts with app (code attached)

Detailed explanation of Js apply ()Usage (including code)

Simple and easy to understand, javascript self-study notes

The above is the detailed content of Problems with adding ! in front of function in js, the code is attached. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!