Home  >  Article  >  Web Front-end  >  Detailed explanation of variable promotion and function promotion in js

Detailed explanation of variable promotion and function promotion in js

小云云
小云云Original
2018-02-06 11:44:591006browse

This article brings you an article on variable promotion and function promotion based on js (detailed explanation). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look, I hope it can help everyone.

1. Variable promotion

Before ES6, JavaScript did not have block-level scope (a pair of curly braces {} is a block-level scope), only global scope and function scope. Variable hoisting hoists a variable declaration to the beginning of its scope.

The example of the previous resume is:


console.log(global); // undefined
var global = 'global';
console.log(global); // global

function fn () {
console.log(a); // undefined
var a = 'aaa';
console.log(a); // aaa
}
fn();

The reason why the above print result is due to the variable promotion of js, in fact, the above code It is executed as follows:


var global; // 变量提升,全局作用域范围内,此时只是声明,并没有赋值
console.log(global); // undefined
global = 'global'; // 此时才赋值
console.log(global); // 打印出global

function fn () {
var a; // 变量提升,函数作用域范围内
console.log(a);
a = 'aaa';
console.log(a);
}
fn();

2. Function improvement

The functions created in js are Two ways: function declaration and function literal. Function hoisting only exists for function declarations! For example:


console.log(f1); // function f1() {}  
console.log(f2); // undefined 
function f1() {}
var f2 = function() {}

The reason why there are the above printing results is because the function promotion in js causes the code to actually be executed as follows:


function f1() {} // 函数提升,整个代码块提升到文件的最开始<br>console.log(f1);  
console.log(f2);  
var f2 = function() {}

Conclusion: That’s basically it. If you want to master it proficiently, you can do more exercises. test:


console.log(f1()); 
console.log(f2);  
function f1() {console.log(&#39;aa&#39;)}
var f2 = function() {}


(function() {
console.log(a);
a = &#39;aaa&#39;;
var a = &#39;bbb&#39;;
console.log(a);
})();

Related recommendations:

Detailed explanation of javascript variable promotion

Detailed explanation of js variable promotion and function declaration pre-parsing examples

In-depth understanding of scope and variable hoisting in JS

The above is the detailed content of Detailed explanation of variable promotion and function promotion in js. For more information, please follow other related articles on the PHP Chinese website!

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