The difference between function declaration and function expression in JavaScript _javascript tips

Source: Internet
Author: User
Tags function definition

Objective

In ECMAScript, there are two of the most commonly used methods of creating function objects, that is, using function expressions or using function declarations. In this regard, the ECMAScript specification makes it clear that a function declaration must always have an identifier (Identifier), which is what we call a function name, and a function expression can be omitted. Here's a look at a detailed distinction between the two.

What is function declaration (functional declaration)?

function declaration You can define named functions variables without assigning values to variables. function declaration is a separate structure that cannot be nested in non-functional modules. It can be likened to a Variable declaration (variable declaration). Just as Variable declaration must begin with "Var", function declaration must begin with "function".

For example

function bar () {return
 3;
}

ECMA 5 (13.0) defines syntax:

function Identifier ( FormalParameterList[opt] ) { FunctionBody }

Function names are available within their scope and parent scope (otherwise they will not be able to get the function).

function bar () {return
 3;
}
 
Bar ()//3
Bar//function

What is function Expression (functional expression)?

function Expression defines functions as part of an expression statement (usually a variable assignment). Functions defined by function Expression can be either named or Anonymous. function Expression cannot begin with "function" (the following example of a call is enclosed in parentheses).

For example

anonymous function Expression
var a = function () {return
 3;
}
 
named function expression
var a = function bar () {return
 3;
}
 
Self invoking Function expression
(function SayHello () {
 alert ("hello!");
}) ();

ECMA 5 (13.0) defines syntax:

function Identifieropt ( FormalParameterList[opt] ) { FunctionBody }

(This definition does not feel complete because it ignores a condition: The outer statement is an expression and does not begin with "function")

The function name (if any) is not available outside the scope of the function (in contrast to function declaration).

What is the Function Statement?

Function Statement are sometimes another way of saying function declaration. But Kangax points out that in Mozilla, function Statement is an extension of function declaration, allowing function declaration statements to be used in any allowed Statement (statements) Place to use. However, Function Statement is not yet a standard, so it is not recommended to be used in product development.

Here we start with some small tests. Guess what happens when the following conditions pop up?

Question 1:

function foo () {
 function bar () {return
 3;
 }
 return bar ();
 function bar () {return
 8;
 }
}
Alert (foo ());

Question 2:

function foo () {
 var bar = function () {return
 3;
 };
 return bar ();
 var bar = function () {return
 8;}
 ;
} Alert (foo ());

Question 3:

Alert (foo ());
function foo () {
 var bar = function () {return
 3;
 };
 return bar ();
 var bar = function () {return
 8;}
 ;
}

Question 4:

function foo () {return
 bar ();
 var bar = function () {return
 3;
 };
 var bar = function () {return
 8;}
 ;
} Alert (foo ());

If your answers are not 8, 3, 3, and [Type Error:bar are not a function], read on ... (even if it's correct, read on.)

Now let's explain the previous test.

Question 1 uses function declaration, which means they get hoisted (promoted) ...

Wait a minute, what is hoisting?

Here's what Ben Cherry says: "function declaration and functions variable (functional variables) are usually moved by the JavaScript interpreter (' hoisted ') to the top of the current scope."

When a function declaration is promoted, the entire body of functions will ascend, so the code for question 1 is interpreted like this after the interpreter:

**simulated processing sequence for question 1**
function foo () {
 //define bar once
 function bar () {
   return 3;
 }
 Redefine it
 function bar () {return
 8;
 }
 Return it invocation return
 bar ();//8
}
alert (foo ());

However, we are often told that the code behind the return statement is not running ...

In the execution of JavaScript, there are two concepts of context (ECMA 5 decomposing it into Lexicalenvironment, variableenvironment and thisbinding) and process (a sequence of called statements). When the program enters the execution domain, declaration can cause variableenvironment. They are different from Statement (such as return) and do not follow the Statement rules.

Will Function Expression be promoted?

This depends on the expression. For example, the first expression in question 2:

var bar = function () {return
 3;
};

The (var bar) to the left of the equal sign is Variable declaration. Variable declaration will be promoted, but assignment Expression (assignment expression) will not. So when the bar is elevated, the interpreter initializes this: var bar = undefined. and the function definition itself is not promoted.

(ECMA 5 12.2 with initialzier (initializer) variables are assigned by Assignmentexpression when Variablestatement executes, not when the variable is created. )

Therefore, the code for Question 2 will run in the following order:

**simulated processing sequence for question 2**
function foo () {
 //a to each function declaration 3/>var bar = undefined;
 var bar = undefined;
 The Expression is executed
 bar = Function () {return
 3;
 };
 Function created by the Expression is invoked return
 bar ();
 Second Function Expression unreachable
}
alert (foo ());//3

You might say, this still explains, but question 3 's answer is wrong, I run the Firebug will be an error.

Save the code in an HTML file, and then try it on Firefox. or run in IE8, Chrome, or Safari consoles. Obviously the Firebug console is in the Global (global) scope, but it's a unique "Firebug" scope--try running "this = = Window" In the Firebug console and you'll know it. When you run the code, the function is not elevated.

The logic of question 3 and question 1 is similar. This time the Foo function was promoted.

Question 4 is simple, there is no function promotion ...

It can be said that, but if there is no elevation at all, TypeError will be "bar not defined" instead of "bar not a function". There is indeed no function elevation in this example, but there are variable elevation. So bar is declared at the beginning, but its value is not defined. The rest of the code is executed sequentially.

**simulated processing sequence for question 4**
function foo () {
 //a to each function declaration 3/>var bar = undefined;
 var bar = undefined;
 return bar (); TypeError: ' Bar not defined '
 //neither Function Expression is reached
}
alert (foo ());

What else should you pay attention to?

It is officially forbidden to use function declaration in non-functional modules, such as if. But all browsers support them, but their interpretations are different.

For example, the following code snippet will be thrown incorrectly in Firefox 3.6 because it interprets function declaration as a function Statement (see above), so x is undefined. But in IE8, Chrome 5 and Safari 5, the function x is returned (just like the standard function declaration).

function foo () {
 if (false) {
 function X () {};
 }
 return x;
}
Alert (foo ());

It can be seen that using Function declaration can cause confusion, so what's the advantage?

You might say that the function declaration is very loose--if you try to use a function before the declaration, ascension can indeed fix the order so that the function can be invoked correctly. But this loosening is not conducive to rigorous coding, and in the long run it is likely to promote rather than prevent accidents from happening. After all, there is a reason why programmers arrange statements in a particular order.

Is there any other reason to support Function Expression?

You know what?

1 Function declaration feels like a Java-style method declaration, but Java methods are not the same as JavaScript. In JavaScript, a function is a living object that contains a value. Java methods are only storage of metadata. The following two pieces of code define a function, but only function Expression looks like the object was created.

function declaration
function Add (a,b) {return a + B};
function Expression
var add = function (a,b) {return a + B};

2 Function Expression more useful. Function declaration can only be isolated as "statement". All it can do is create an object variable in the current scope. By contrast, Function Expression (by definition) is part of a large structure. You can use function Expression if you want to create anonymous functions, add functions to prototype (prototypes), or use functions as property (properties) for other objects. Each time you create a new function using a higher-order application, such as curry or compose, you are using function Expression. function Expression and functional programming (functional programming) are inseparable.

Function Expression
var sayhello = Alert.curry ("hello!");

Do Function Expression have drawbacks?

Function Expression creates most of the functions that are anonymous. For example, the following function is anonymous, and today is just a reference to an anonymous function:

var today = function () {return new Date ()}

Is this going to be a problem? Not in most cases, but as Nick Fitzgerald points out, debugging anonymous functions can be annoying. He recommends using the Named Function Expressions (nfes) as the workspace:

var-today = function today () {return new Date ()}

However, as Asen Bozhilov said (and Kangax documentation) NFES is not executed correctly under IE9.

Conclusion

Arbitrary function declaration are misleading and rarely (if any), assigning values to variables with function Expression cannot replace the function declaration. However, if you must use function declaration, placing it at the top of the owning scope can reduce confusion. Never put a Function declaration in an if statement.

The

says so much, perhaps in your own case, Function declaration is still very useful. It's nothing. Rote dogma is dangerous and usually causes the code to beat around the bush. More importantly, you understand the concept so that you can decide which way to create the function, depending on your situation. The above is the entire content of this article, I hope this article is helpful to everyone in this respect.

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.