


In-depth interpretation of the Hoisting mechanism in JavaScript_Basic knowledge
hoisting mechanism
Javascript's variable declaration has a hoisting mechanism. When the JavaScript engine is executed, it will raise all variable declarations to the front of the current scope.
Look at a piece of code first
var v = "hello"; (function(){ console.log(v); var v = "world"; })();
What is the result of running this code?
The answer is: undefined
This code illustrates two problems,
First, the variable v in the function scope covers the upper scope variable v. Make less changes to the code
var v = "hello"; if(true){ console.log(v); var v = "world"; }
The output result is "hello", indicating that JavaScript does not have block-level scope. Functions are the only structures in JavaScript that have their own scope.
Second, within the function scope, the declaration of variable v is promoted. So the initial code is equivalent to:
var v = "hello"; (function(){ var v; //declaration hoisting console.log(v); v = "world"; })();
Declaration, definition and initialization
The declaration declares the existence of a name, the definition allocates storage space for the name, and the initialization assigns an initial value to the storage space allocated by the name.
Use C to express these three concepts
extern int i;//This is a statement indicating that the name i already exists somewhere
int i;//This is to declare and define the name i, and allocate storage space for i
i = 0;//This is the initialization name i, assigning an initial value of 0
This is the case in javascript
var v;//Declare variable v
v = "hello";//(define and) initialize variable v
Because JavaScript is a dynamic language, its variables do not have a fixed type, and the size of its storage space changes with initialization and assignment. Therefore, the "definition" of its variables is not the same as that of traditional static languages, and its definition is irrelevant.
Declaration of promotion
Declarations within the current scope will be promoted to the front of the scope, including declarations of variables and functions
(function(){ var a = "1"; var f = function(){}; var b = "2"; var c = "3"; })();
The declaration of variables a, f, b, c will be promoted to the front of the function scope, similar to the following:
(function(){ var a,f,b,c; a = "1"; f = function(){}; b = "2"; c = "3"; })();
Please note that function expressions are not promoted, which is also the difference between function expressions and function declarations. Let’s take a closer look at the differences between the two:
(function(){ //var f1,function f2(){}; //hoisting,被隐式提升的声明 f1(); //ReferenceError: f1 is not defined f2(); var f1 = function(){}; function f2(){} })();
The function declaration f2 in the above code is promoted, so there is no problem in calling f2 earlier. Although the variable f1 is also promoted, the value of f1 after promotion is undefined, and its real initial value is assigned when the function expression is executed. So only the statement is promoted.
Name resolution order
A name in JavaScript enters the scope in four ways, and their priority order is as follows:
1. Language built-in: all scopes have this and arguments keywords
2. Formal parameters: The parameters of the function are valid in the function scope
3. Function declaration: in the shape of function foo() {}
4. Variable declaration: in the form of var bar;
The priority of name declaration is as shown above, that is, if the name of a variable is the same as the name of the function, then the name of the function will override the name of the variable, regardless of its order in the code. However, the names are initialized in the order in which they are written in the code, and are not affected by the above priorities. Look at the code:
(function(){ var foo; console.log(typeof foo); //function function foo(){} foo = "foo"; console.log(typeof foo); //string })();
If there are multiple variables with the same name in the formal parameters, the last parameter with the same name will overwrite the other parameters with the same name, even if the last parameter with the same name is not defined.
There are exceptions to the above name resolution priorities, such as the ability to override the language's built-in name arguments.
Named function expression
A function expression can be given a name just like a function declaration, but this does not make the function expression a function declaration. The name of a named function expression does not enter the namespace and is not promoted.
f();//TypeError: f is not a function
foo();//ReferenceError: foo is not defined
var f = function foo(){console.log(typeof foo);};
f();//function
foo();//ReferenceError: foo is not defined
The name of a named function expression is only valid within the scope of the function.
Let’s take a look at the following example:
var myval = "my global var"; (function() { console.log(myval); // log "my global var" })();
The above code will obviously output "my global var", but if we slightly modify the above code as follows:
var myval = "my global var"; (function() { console.log(myval); // log "undefined" var myval = "my local var"; })();
The execution result is that an undefined is output. The reason for this result is that the variable declaration is promoted. The above code is equivalent to the following:
var myval = "my global var"; (function() { var myval; console.log(myval); // log "undefined" myval = "my local var"; })();
Only the declaration part of the variable is promoted and is not initialized immediately, so undefined will be output.
However, this promotion mechanism is not only reflected in ordinary variables, but also in functions. For example, the following code cannot be executed correctly:
(function() { fun(); // Uncaught TypeError: undefined is not a function var fun = function() { console.log("Hello!"); } })();
Because it is equivalent to:
(function() { var fun; fun(); // Uncaught TypeError: undefined is not a function fun = function() { console.log("Hello!"); } })();
Because the declaration of the function is also hoisted and not initialized immediately, an error occurs.
Of course, this way of defining a function is called a "function expression" and there will be a promotion mechanism. If it is the following "function declaration" method, there will be no problems with the promotion mechanism at all:
(function() { fun(); function fun() { console.log("Hello!"); // log "Hello!" } })();
This is also the main difference between function declaration and function expression.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
