JS function definition and anonymous function invocation

Source: Internet
Author: User

There are three ways to define a function:

1. Keyword method

function Fnmethodname (x) {    alert (x);}

2. Literal method

var function (x) {    alert (x);}

3.Function () constructor

var New Function (' x ', ' Alert (x); ')
The above three methods define the same method function Fnmethodname, the 1th is the most commonly used method, the latter two are to copy a function to the variable fnmethodname, and this function is no name, that is, anonymous function.

4. Defining anonymous Functions

<body onload= "alert (' http://www.baidu.com/');" >  <script type= "Text/javascript" >  voidfunction()  {      alert (' Pop-up box ');  } ();   </script>  two notation <body onload= "alert (' http://www.baidu.com/');" >  <script type= "Text/javascript" >  (function()  {      alert ( ' popup box ');  }) ();   </script>  

A function with no function name, which extends the question of how to invoke an anonymous function.

Parentheses call

Why is this method successfully invoked?
The effect of parentheses:

Parentheses can combine our expressions and each block, that is, each pair of parentheses, has a return value. This return value is actually the return value of the expression in parentheses.

So, when we enclose the anonymous function with a pair of parentheses, the parentheses are actually returned, which is the function object of one of the anonymous functions.

Therefore, the parenthesis pair plus the anonymous function is like the name of the function that we get its reference position. So if you add a parameter list after the reference variable, the invocation form of the normal function is implemented.

JS function definition and anonymous function invocation

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.