Home  >  Article  >  Web Front-end  >  JavaScript Scoping and Hoisting Translation_javascript skills

JavaScript Scoping and Hoisting Translation_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:52:081149browse

Do you know what value the alert will output after the following JavaScript code is executed?

Copy code The code is as follows:

var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();

If the answer "10" surprises you, then this may confuse you even more:
[/code]
var a = 1;
function b() {
a = 10 ;
return;
function a() {}
}
b();
alert(a);
[/code]
The browser will alert "1 ". So, what happened? Although this may seem a little strange, a little dangerous, and a little confusing, it's actually a powerful expressive feature of the language. I don't know if there is a standard that defines this behavior, but I like to use "hoisting" to describe it. This article tries to explain this mechanism, but first, let’s do some necessary understanding of JavaScript scoping.
Scoping in JavaScript
Scoping is one of the most confusing parts for JavaScript newbies. In fact, not just newbies, I've met many experienced JavaScript programmers who can't fully understand scoping. The reason JavaScript scoping is so complex is that it looks very much like a member of the C family of languages. Please look at the following C program:
Copy the code The code is as follows:

#include
int main() {
int x = 1;
printf("%d, ", x); // 1
if (1) {
int x = 2;
printf("%d, ", x); // 2
}
printf("%dn", x); // 1
}

The output of this program is 1,2,1. This is because there is a block-level scope in C-series languages. When entering a block, just like an if statement, new variables will be declared in this block-level scope. These variables will not affect outer scope. But this is not the case with JavaScript. Try the following code in Firebug:
Copy the code The code is 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 has function-level scope. This is completely different from C-based languages. Blocks, like if statements, do not create a new scope. Only functions create new scopes.
For most programmers familiar with C, C#, C# or Java, this is unexpected and unwelcome. Fortunately, because of the flexibility of JavaScript functions, we have a solution to this problem. If you must create a temporary scope in a function, do it like this:
Copy the code The code is 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, it can be used to create any A place of temporary scope, not just within a block. However, I strongly recommend that you take the time to understand JavaScript scoping. It's really powerful, and it's one of my favorite features of the language. If you understand scoping well, it will be easier to understand hoisting.
Declarations, Names, and Hoisting
In JavaScript, there are four types of names in a scope:
1. Language-defined: all functions The field will contain this and arguments by default.
2. Formal parameters: Function parameters with names will enter the scope of the function body.
3. Function decalrations: in the form of function foo() {}.
4. Variable declarations: in the form of var foo;.
Function declarations and variable declarations are always implicitly hoisted by the JavaScript interpreter to the top of the scope that contains them. Obviously, the language's own definition and function parameters are already at the top of the scope. This is like the following code:
Copy the code The code is as follows:

function foo() {
bar();
var x = 1;
}

is actually interpreted like this:
Copy code The code is as follows:

function foo() {
var x;
bar();
x = 1;
}

The result is that it has no effect whether the statement is executed or not. The following two pieces of code are equivalent:
Copy the code The code is as follows:

function foo () {
if (false) {
var x = 1;
}
return;
var y = 1;
}
function foo() {
var x, y;
if (false) {
x = 1;
}
return;
y = 1;
}

Notice that the assignment part of the declaration is not hoisted. Only the declared name is promoted. This is different from function declarations, where the entire function body is also hoisted. But remember, there are generally two ways to declare a function. Consider the following JavaScript code:
Copy the code The code is as follows:

function test() {
foo(); // TypeError "foo is not a function"
bar(); // "this will run!"
var foo = function () { // Function expression is assigned to a variable 'foo'
alert("this won't run!");
}
function bar() { // Function declaration named 'bar'
alert("this will run! ");
}
}
test();

Here, only the function declaration will be promoted together with the function body, while the function expression will only be promoted The name and function body will only be assigned when the assignment statement is executed.
The above covers all the basics of hoisting. It doesn’t seem that complicated or confusing, right? However, this is JavaScript, and there are always going to be a little complications in some special cases.
Name Resolution Order
The most important special case to remember is the name resolution order. Remember that there are four ways for a name to enter a scope. The order I listed above is the order in which they parse. In general, if a name is already defined, it will never be overwritten by another name with the same name that has different attributes. This means that function declarations have higher priority than variable declarations. But this does not mean that the assignment to this name is invalid, it is just that the declared part will be ignored. There are a few exceptions:
The built-in name arguments behave a little weirdly. It seems to be declared after the formal parameters and before the function declaration. This means that the formal parameter named arguments will have higher priority than the built-in arguments, even if the parameter is undefined. This is a bad feature, do not use arguments as formal parameters.
Any attempt to use this as an identifier will cause a syntax error, which is a good feature.
If there are multiple formal parameters with the same name, the parameter at the end of the list has the highest priority, even if it is undefined.
Name Function Expressions
You can define a name for a function in a function expression, just like a function declaration statement. But this does not make it a function declaration, and the name is not introduced into the scope, and the function body is not hoisted. Here's some code to illustrate what I mean:
Copy code Here's the code:

foo(); // TypeError "foo is not a function"
bar(); // valid
baz(); // TypeError "baz is not a function"
spam(); / / ReferenceError "spam is not defined"
var foo = function () {}; // Anonymous function expression ('foo' is promoted)
function bar() {}; // Function declaration ('bar ' and the function body are promoted)
var baz = function spam() {}; // Named function expression (only 'baz' is promoted)
foo(); // valid
bar() ; // valid
baz(); // valid
spam(); // ReferenceError "spam is not defined"

How to Code With This Knowledge
Now you Now that you understand scoping and hoisting, what does this mean for writing JavaScript code? The most important one is to always use the var statement when declaring variables. I strongly recommend that you only use one var at the top of each scope. If you force yourself to do this, you will never be troubled by promotion-related problems. Although doing so makes it more difficult to keep track of which variables are actually declared in the current scope. I recommend using the onevar option in JSLint. If you do all the previous suggestions, your code will look like this:
Copy the codeThe code will look like this:

/*jslint onevar: true [...] */
function foo(a, b, c) {
var x = 1,
bar,
baz = "something";
}

What the Standard Says
I find it always useful to refer directly to the ECMAScript Standard (pdf) to understand how these things work it works. The following is an excerpt about variable declaration and scope (section 12.2.2):
If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, as described in section 10.1.3 . Otherwise, they are defined with global scope (that is, they are created as members of the global object, as described in section 10.1.3) using property attributes { DontDelete }. Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.

I hope this article can shed some light on the most confusing part of JavaScript programmers. I tried my best to write it comprehensively so as not to cause more confusion. If I made a mistake or missed something important, please let me know.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn