In-depth analysis of the plus signs and exclamation points before JavaScript Functions, analysis of javascript

Source: Internet
Author: User
Tags js function declaration

In-depth analysis of the plus signs and exclamation points before JavaScript Functions, analysis of javascript

+ Function (){}();

The plus sign can also be replaced !,~ And other unary operators, the effect is equivalent:

(Function () {console. log ("Foo! ") ;}) (); // Or (function () {console. log (" Foo! ");}());

Without this plus sign, the parser considers the function as the beginning of a function declaration, and the following () will cause a syntax error. When the + sign is added before the function, it becomes a function expression, and a () is added after the function expression to become a function that is executed immediately.

Let's take a look at the role of the exclamation point in front of the js function:

I. JS function declaration form

Function fnA () {alert ('msg ');} // declarative function Definition

Ii. JS function expression form

Var func = function (agr1, arg2) {// create an anonymous function alert (arg1 + ''+ arg2 );}

Iii. Common Format of immediate execution after JS anonymous function declaration

(Function () {/* code */})();

Description

1. The first pair of parentheses in the function () {}) returns the Untitled function to the script, and then an empty pair of parentheses immediately executes the returned untitled function. The parameters in the brackets are anonymous function parameters.

2. use parentheses to wrap the definition function body. The parser will call the definition function in the form of a function expression. That is to say, any way to convert a function into a function expression can make the parser correctly call and define a function. And! Is one of them, and +-| has such a function.

3. The function is mainly used for anonymous and automatic execution.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.