Pre-parsing stage: In the pre-parsing stage, js will promote variables declared with var and statement blocks starting with function, and var will be promoted. Declared variables and functions are promoted to the front of the code. It should be noted that the function is promoted as a whole. Variables declared by var only promote the variable declaration, and assignment operations will not be performed at the same time.
Execution phase
alert(a)//undefinedvar a = 1; 为什么会输出undefined呢? 模拟提升的之后的代码 ,上一段代码相当于 var a; //声明一个变量。但是没有初始化Alert(a); a = 1; //初始化为1---------- fun(); //在C语言中,如果不先声明函数,先调用后声明函数会报错,但是js会正常运行function fun(){ alert(“函数被声明了”); } 代码提升后 相当于 function fun(){ alert(“函数被声明了”); } fun();
func1(); //输出 我是后声明的函数function func1(){ console.log('我是先声明的函数'); }function func1(){ console.log('我是后声明的函数'); } 模拟提升后的代码function func1(){ console.log('我是先声明的函数'); }function func1(){ console.log('我是后声明的函数'); } func1(); 函数名也是变量,后面的会覆盖前面。
alert(foo); //输出function foo(){}function foo(){ } var foo = 2; alert(foo); //输出 2----------模拟提升后的代码function foo{}Alert(foo); foo = 2; alert(foo);
var num = 123; function test(){ console.log(num); var num = 10; } test(); //输出undefined; ---------- 模拟变量提升后的代码 var num;function test(){var num console.log(num); //函数内部声明了num,但是没赋值。因为在函数内部声明了num,所以函数会使用它内部声明的num,而不会去全局中找 num = 10; } num = 123;
func(); // func is not a function var func = function(){ alert("1234"); } ---------- 提升后的代码var func; func(); func = function(){ alert("1234"); }; 用var声明的变量(包括函数表达式),只提升声明,不提升赋值操作
var s1 = “qq”;
foo(); function foo() { console.log(s1); var s1 = "tengxunqq"; console.log(s1);
}
提升后: var s1; function foo() { var s1; console.log(s1); // s1= "tengxunqq"; console.log(s1); //t } s1 = "qq"; foo(); //先输出 undefined 后engxunqq
Related recommendations:
Introduction to JS variables and their scope knowledge points
Detailed explanation of js variable promotion and function declaration pre-parsing examples
The above is the detailed content of Detailed explanation of js variable promotion. For more information, please follow other related articles on the PHP Chinese website!