function declarations and function expressions

Source: Internet
Author: User

1. What is a function declaration, function expression

Functions declaration: Function Function name () {}

Functional expression: Function name () {}. The function name can be written without writing. Written, is named function expression, do not write is anonymous function expression

Example:

function aaa () {};

var a=function aaa () {}; named function expression

var a=function () {}; anonymous function expression

The following are all function expressions

(function aaa () {})

~function aaa () {}
-function aaa () {}
+function aaa () {}
!function aaa () {}

2. Differences

(1) The function expression can be executed directly after the parentheses, and the function declaration is not possible.

function aaa () {alert (1);} ();//function declaration not possible, result has error var a=function aaa () {alert (1);} ();//function expression Yes, result pop-up 1

~ function aaa () {alert (1);} ();//function expression Yes, result also popup 1

(2) function declaration can be resolved in advance

As in the following example: 1 is popped in Firefox, but 2 is popped in IE, but there is no such thing as a function expression. So in this case, use the function expression.

if (true) {    function aaa () {        alert (1);    }} else{        function aaa () {        alert (2);    }} AAA ();

Using function Expressions:

if (true) {    var a = function aaa (){        alert (1);    }} else{        var a = function aaa (){        alert (2);    }} a ();//with AAA (); Can you? No!

All that pops up is 1.

So the question is, why not use AAA (), because the AAA () is not found outside the call, but can be found in the interior.

For function expressions, do not use;

var a=function aaa () {    alert (1);    Alert (typeof AAA);} AAA ();

Results show

var a = function aaa () {    alert (1);    Alert (typeof AAA);  Inside is the}a () that can be found;/*aaa ();  I can't find it outside.

function declarations and function expressions

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.