预解析阶段:在预解析阶段,js会对以var声明的变量,和function开头的语句块进行提升,将var声明的变量和function 提升至代码的最前面。需要注意的时,function整体提升,var 声明的变量只提升变量声明,并不会在提升的同时进行赋值操作
执行阶段
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相关推荐:
云优YUNUCMS企业网站管理系统三网合一,跨平台兼容,让企业快速、高效的展示在广大客户面前,为企业带来更多潜在客户,提升企业曝光率和品牌影响力。 云优YUNUCMS企业网站管理系统 1.1.2 更新日志:2018-08-02 [新增]表单邮件提醒增加携带变量; [新增]htm和txt格式站点地图文件,每次登录后台自动生成; [新增]数据统计主菜单; [新增]集成平台主词排名监控;
829
以上就是js变量提升详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号