On the difference between JavaScript function expression and function declaration _javascript skill

Source: Internet
Author: User

There are two ways to declare functions in javascript: function declarations and function expressions.

The difference is as follows:

1. Functions defined by the method declared by the function, the function name is required, and the function expression of the function name is optional.

2. Functions defined by the method declared by the function, functions can be called before the function declaration, and function expression functions can only be called after the declaration.

3. Functions defined by the method of the function declaration are not true declarations, they can only appear in the global, or nested in other functions, but they can not appear in the loop, condition or try/catch/finally, and

A function expression can be declared anywhere.

There are two ways to define a function, respectively:

 Function-declared functions
 greeting () {
    console.log ("Hello World"); 
 }
 
 
 Functional expression
 var greeting = function () {
   console.log ("Hello World"); 
 }

Here's an interesting javascript:

function f () {Console.log (' I am outside! ');}
(function () {
 if (false) {
  ///Repeat once functions f
  () {console.log (' I am inside! ')}
 f ();
} ());

What does it output? The first reaction should be "I am outside". Results in chrome output "I am inside", IE11 direct error, Firefox lower version of the output "I am outside" ...

The results of the chrome output clearly reflect the features of functions declared with function declarations-functions that can be invoked before they are declared.

The IE error shows missing objects because the function declaration is in the condition and violates the principle of the function declaration.

Scope of function Expressions:

If a function expression declares a function that has a function name, then the function name is equivalent to a local variable of this function, which can only be invoked inside the function, lifting a chestnut:

var f = function fact (x) { 
        if (x <= 1) return 
          1;
        else return 
          x*fact (x-1);
        Alert (fact ());  Uncaught referenceerror:fact is not defined

Fact () can be invoked inside a function, and an error is invoked outside the function: fact undefined.
Fact

Let's take a look at the details.

function declaration

Function Sound Example code

The code is as follows:

function fn () {
  console.log (' fn function execution ... ');
  Code..
}

So we're going to declare a function called FN, and here's a thought, do you think that calling him on the top of this function will execute? Or do you have an error?

The code is as follows: FN (); In the previous call we declared the FN function function fn () {console.log (' fn function execution ... ');//Code ...}

Console output Results:

Yes, at this point the FN function can be invoked, here to summarize the reason.

Summarize:

1: At this point the FN function is the result of the variable, which is stored in the global context variable (available window. function name to validate)

2: This way is the function declaration, which is created in the global context phase, and is already available in the code execution phase. Ps:javascript initializes the context environment (by global → Local) Every time the method is entered.

3: It can affect variable objects (only the variables stored in the context are affected)

function expression

function Expression Sample Code

The code is as follows:

var fn = function () {
  console.log (' fn function ' expression declaration execution ... ')
  Code..
}

So we declare an anonymous function and point its reference to the variable fn?

Once again, call the upper and lower sides of the function declared by the expression to see the output of the console.

The code is as follows:

In order to see the output of the console clearly, we make a mark before and after each call to increase the readability.
Console.log (' Before call begins ... ');
fn ();
Console.log (' Before call ends ... ');
var fn = function () {
  console.log (' fn function ' expression declaration execution ... ')
  Code..
}
Console.log (' After call begins ... ');
fn ();
Console.log (' After call begins ... ');

Console Print Results:

You can see that the code, when it executes to the first invocation of the FN () function, is prompted that the FN is not a function (FN isn't a method), and that the operation terminates when an error is encountered.

This means that when the first invocation of FN (), the var fn variable does not exist as a property of the global object, and the anonymous function context of the FN reference is not initialized, so the call failed before him.

The code is as follows:

Now let's comment out the previous call logic, and then look at the console output
//  Console.log (' Before the call begins ... ');  fn ();  Console.log (' Before call ends ... ');
  var fn = function () {
    console.log (' fn function ' expression declaration execution ... ')
    Code..
  }
  Console.log (' After call begins ... ');
  FN (); Call Console.log after the expression
  (' After call begins ... ');

Console Print Results:

As you can see, it's OK to call after the expression function, to sum up what is that?

Summarize:

1: First the variable itself does not exist as a function, but rather a reference to an anonymous function (a value type that is not part of a reference)

2: In the code execution phase, when initializing the global context, it does not exist as a global attribute, so it does not pollute the variable object

3: This type of declaration is generally more common in the development of Plug-ins, but also as a callback function in the closure of the call

Therefore, the function fn () {} is not equal to the var fn = function () {}, they are essentially different.

The above is the entire content of this article, the idea is very clear, the contrast is very clear, is a very good article, small partners must be carefully studied under

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.