Variable lift------hoisting in JavaScript

Source: Internet
Author: User

This article was transferred from Damonlan article http://www.cnblogs.com/damonlan/archive/2012/07/01/2553425.htmlObjective

Because I am writing this article, Baidu Search for information, found a friend of the garden article, write very good, but I wrote and do not want to give up, so in the inside took a lot of things come! ~~

Translation JavaScript Scoping and hoisting

We hope to be forgiven.

Because this problem is very classic, and error prone, so in the introduction. Ha ha. No, it's weird.

One. Crime scene

Let's first look at a very simple code:

varv=‘Hello World‘;alert(v);

There's no doubt about it, pop "Hello World". OK, let's continue.

We're looking at a code:

var v= ' Hello World ';(function () {    alert (v);}) ()

After running, we found that, as we expected, the "Hello world" popped up.

Okay, here's the fun. Then look at the following code:

var v= ' Hello World ';(function () {    alert (v);    var v= ' I love You ';}) ()

If this is a face test, what is the result of the interviewer asking you? What's your answer?

Let's see the results first!

The result is undefined? Is it the same as what you think above?

Well, I'm not going to be a trick. In fact, this hides a trap-----variable elevation in JavaScript (hoisting);

Two. Depth analysis

Now, let me explain what ascension means. As the name implies, the following things are mentioned above. In JS, it is defined in the back of the east (variable or function) to the previous definition.

Before explaining the promotion, let's take a look at the scope (scoping) problem in JS.

For JavaScript novices, scoping is one of the most confusing parts. In fact, not only the novice, I met or a lot of experienced JavaScript programmers do not fully understand scoping. The reason for the complexity of JavaScript's scoping is that it looks very much like a member of the C-system language. Please see the following C program:

#include <stdio.h>    int main () {    int x = 1;    printf ("%d,", x); 1    if (1) {        int x = 2;        printf ("%d,", x); 2     }    printf ("%d\n", x);//1}

The output of this program is 1,2,1. This is because in the C-system language there is a block-level scope (block-level scope), when entering a block, like an if statement, a new variable is declared in this block-level scope, and these variables do not affect the external scope. But JavaScript is not like that. Try the following code in Firebug:

var x = 1;    Console.log (x); 1 if (true) {   var x = 2;   Console.log (x); 2} console.log (x);//2

In this code, Firebug displays 1,2,2. This is because JavaScript is a function-level scope (function-level scope). This is completely different from the C-system language. block, just like the IF statement, does not create a new scope. Only the function creates a new scope.

For most programmers who are familiar with c,c++,c# or Java, this is unexpected and not to be seen. Fortunately, because of the flexibility of JavaScript functions, we have a solution to this problem. If you have to create a temporary scope in the function, do this as follows:

function foo () {    var x = 1;    if (x) {        (function () {            var x = 2;            Some other Code        } ());    }    X is still 1.}

This aspect is really very flexible, and it is used wherever you need to create a temporary scope, not just in a block. However, I strongly recommend that you take some time to understand the JavaScript scoping. It's really powerful, and it's one of my favorite language features. If you understand scoping well, it will be easier to understand hoisting.

2.1 Variable Promotion

Variable elevation is simply the place where the variable is raised to the top of the function. What I need to make clear is that the variable promotion is just the declaration of the promoted variable and does not raise the assignment.

Like what:

We define three variables:

(function () {    var a= ' one ';    var b= ' both ';    var c= ' three ';}) ()

In fact, it's like this:

(function () {    var a,b,c;    A= ' one ';    B= ' both ';    C= ' three ';}) ()

This is the time to raise the variable.

OK, let's go back to the first code. Why did you get an error? In fact, according to the above variables to enhance the original and the scope of JS (block-level scope) analysis, that the above code really becomes the following:

var v= ' Hello World ';(function () {    var V;    Alert (v);    v= ' I love You ';}) ()

Therefore, will be prompted to say "undefined".

From here, we also learn that when we write JS code, I need to put the variable at the top of the function-level scope, such as the example I mentioned above: Var a,b,c; To prevent accidental occurrences.

2.2 Function Promotion

function promotion is to refer the whole function to the front.

When we write JS code, we have 2, one is the function expression, and the other is the function declaration method. It is important to note that only the function declaration form can be promoted.

function declaration promoted "success"

function MyTest () {    foo ();    function foo () {        alert ("I am from foo");}    } MyTest ();

function expression promoted "failed"

function MyTest () {    foo ();   var foo =function foo () {        alert ("I'm from Foo");}    } MyTest ();

The results are as follows:

Left an error. I didn't lie to you.

Should be here basically can understand. ~

Oh..

Thanks again beta Rabbit

Variable lift------hoisting in JavaScript

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.