Detailed JavaScript function traps

Source: Internet
Author: User

Javascript function is ubiquitous and powerful! JavaScript functions allow JS to have some object-oriented features, such as encapsulation, inheritance, and so on, can also be used to reuse code. But there are two sides to things, JavaScript functions sometimes more "wayward", if you do not understand its "temperament", it is likely to give you to create some unexpected trouble (bugs) out.

There are two types of J avascript function:

1) function declaration (functions Declaration);

    // function Declaration    function fundeclaration (type) {        return type=== "Declaration";    }

2) function expression.

    // function Expression    var function (type) {        return type=== "Expression";    }

The code above looks very similar and doesn't feel much different. But in fact, a "trap" on JavaScript functions is embodied in JavaScript two types of function definitions. Here's a look at two pieces of code (labeled Code 1 and Code 2, respectively):

 1  Fundeclaration ("Declaration"); // => true  2  function   Fundeclaration (type) { 3  return  type=== "Declaration" ;  4 }  
 1  Funexpression ("Expression"); // =>error  2  var  funexpression = function   3  return  type=== "Expression" ;  4 }  
  functions created with function declarations Fundeclaratio n can be called before fundeclaration , whereas funexpression functions created with function expressions cannot be funexpression  is called before the value is assigned.  
Why is this?! This is to understand the difference between JavaScript function two types: with creates functions that are assigned at run time and are not invoked until the expression assignment is complete. The difference between
seems small, but in some cases it is a trap that is hard to find. of both types (at parse time/run time) differences . For variable elevation, see my other blog post, http://www.cnblogs.com/isaboy/p/javascript_hoisting.html. The above two code function promotion can be shown as:

Code 1 segment JS function equivalent to:
    function fundeclaration (type) {        return type=== "Declaration";    }    Fundeclaration ("Declaration"); // = True
The code 2 Segment JS function is equivalent to:
    var funexpression;    Funexpression ("Expression"); // ==>error    function (type) {        return type=== "Expression";    }

At run time, the code above defines only the funexpression variable, but the value is undefined. Therefore, you cannot make a function call on undefined. At this point the funexpression assignment statement has not been executed. To further deepen the difference between the two types of JS functions, here is a more confusing example, see the following code (code snippet 4):

1     varSayHello;2Console.log (typeof(Sayhey));//=>function3Console.log (typeof(Sayho));//=>undefined4     if(true) {5         functionSayhey () {6Console.log ("Sayhey");7         }8SayHello =functionSayho () {9Console.log ("SayHello");Ten     } One}Else { A         functionSayhey () { -Console.log ("SayHey2"); -         } theSayHello =functionSayho () { -Console.log ("SayHello2"); -         } -     }     +Sayhey ();//= SayHey2 -SayHello ();//= SayHello

  Analysis : Sayhey is created with a function declaration, the JS compiler in the JS parsing function definition of function promotion, that is, in parsing the JS code, JS compiler (conditional judgment does not form a new scope, Two Sayhey function definitions are promoted beyond the conditional judgment) detects that there are two sayhey definitions with the same name in the scope, the first one is promoted first, the second definition is then promoted (the second definition is under the first definition), and the second definition overrides the first sayhey definition, So Sayhey () output SayHey2, and SayHello is created with a function expression, the content of its expression is in the JS runtime (not parsing) to determine (here the condition is played), so the SayHello expression executes the first function definition and assign a value, The SayHello () output SayHello.

  Code Snippet 4 is actually equivalent to the following code (code snippet 5):

1     varSayHello;2     functionSayhey () {3Console.log ("Sayhey");4         }5     functionSayhey () {6Console.log ("SayHey2");7     }8Console.log (typeof(Sayhey));//=>function9Console.log (typeof(Sayho));//=>undefinedTen     if(true) { One         //Hoisting ... ASayHello =functionSayho () { -Console.log ("SayHello"); -     } the}Else { -         //Hoisting ... -SayHello =functionSayho () { -Console.log ("SayHello2"); +         } -     }     +Sayhey ();//= SayHey2 ASayHello ();//= SayHello

  Some people may suspect that the definition of function Sayhey is the second one covering the first one? We can output the source code of Sayhey , there is a picture of the truth, as shown in:

Summarize

There is a difference between function declarations and function expressions in Javascript, function declarations are promoted in JS parsing , so in the same scope, the function can be called regardless of where the function declaration is defined. The value of the function expression is determined at the JS runtime and is called after the expression assignment is complete. This tiny difference may lead to unexpected bugs appearing in the JS code, leaving you trapped in inexplicable traps.

Finally , we enclose the core steps of the two functions of SayHello and Sayhey in code Snippet 4 ( personal Understanding, if there are objections welcome message discussion ):

The main steps to perform for the SayHello function.

Perform the main steps for the Sayhey function. If you are interested in closures, you can read another blog post http://www.cnblogs.com/isaboy/p/javascript_closure.html.

Detailed JavaScript function traps

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.