Hoisting_javascript techniques for variable elevation in JavaScript

Source: Internet
Author: User
Tags javascript hoisting
Because I am writing this article, Baidu find information, find a garden friend of an article, write very well, but I wrote and do not want to give up, so in the inside took a lot of things over! ~~

Translation JavaScript Scoping and hoisting

I hope we can understand you.

one. The scene of the crime

Let's look at a simple piece of code:
Copy Code code as follows:

var v= ' Hello World ';
Alert (v);

This is no doubt, pop "Hello World". OK, let's move on.

We're looking at a code:
Copy Code code as follows:

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:
Copy Code code as follows:

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

If this is a face test, the interviewer asks you what the result is? What do you say?

Let's see the results first!

The result is undefined? Is that what you think it is?

Well, I'll be fine. In fact, it hides a trap-----The variable elevation in JavaScript (hoisting);

two. Depth Analysis

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

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

Scoping is one of the most confusing parts for JavaScript novices. In fact, not only novice, I met or a lot of experienced JavaScript programmers can not fully understand scoping. The reason JavaScript's scoping is so complicated is that it looks very much like a member of the C-system language. Take a look at the C program below:

Copy Code code as follows:

#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), which, when entered into a block, is like an if statement, where a new variable is declared in the block-level scope, which does not affect the external scope. But that's not what JavaScript is. Try the following code in the Firebug:

Copy Code code as follows:

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, and does not create a new scope. Only a function creates a new scope.

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

Copy Code code as follows:

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


This aspect is indeed very flexible, and it is used in any place where you need to create a temporary scope, not just in a block. However, I strongly recommend that you take the time to understand the JavaScript scoping. It's really strong, and it's one of my favorite language features. If you have a good understanding of scoping, it will be much easier to understand hoisting.

2.1 Variable Elevation
The variable elevation, very simply, is the place where the variable elevation refers to the top of the function. What I need to explain is that variable elevation is just a declaration of ascending variables and does not raise the value of the assignment.

Like what:

We define three variables:
Copy Code code as follows:

(function () {
var a= ' one ';
var b= ' two ';
var c= ' Three ';
})()

In fact, it's like this:

Copy Code code as follows:

(function () {
var a,b,c;
A= ' one ';
B= ' two ';
c= ' Three ';
})()

This is the time to elevate the variable.

OK, now we're back in the first code. Why do you have an error? In fact, according to me according to the above variables to promote the original and JS scope (block-level scope) of the analysis, learned that the above code really becomes as follows:
Copy Code code as follows:

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

Therefore, will be prompted to say "undefined".

From here, we also learned that when we write the JS code, I need to put the variables at the top of the block-level scope, such as I cited above example: Var a,b,c; Prevent unexpected occurrences.

2.2 Function elevation
Function elevation is to refer the entire function to the front.

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

function declaration method to promote "success"

Copy Code code as follows:

function MyTest () {
Foo ();
function foo () {
Alert ("I'm from Foo");
}
}
MyTest ();


function expressions promote "failed"

Copy Code code as follows:

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

The results are as follows:

There is an error on the left. I didn't lie to you.

Should be here to understand the basic. ~
Oh..
Thanks again beta Rabbit

Author: lanny☆ Landong only
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.