Do you know what value the alert will output after the following JavaScript code is executed?
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:
#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:
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:
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:
function foo() {
bar();
var x = 1;
}
is actually interpreted like this:
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:
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:
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:
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:
/*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.

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
