您的位置:首页 > 其它

变量和函数提升

2016-12-15 22:05 148 查看
聊聊变量和函数的提升,按照自己的理解通俗的说出来。

变量的提升

1     console.log(num); //输出undefined
2     var num = 1;
3     //等价于
4     var num;
5     console.log(num); //输出undefined
6     num = 1;


变量提升好理解,javascript在执行代码的时候会首先把页面声明的全局变量提升到最前面,但是值没有提升,只是把申明放在了前面,所以输出了undefined

函数的提升

1     test()
2     function test(){
3         console.log("test function");
4     }
5     //---------------------我是分割线--------------------------------------
6     //等价于
7     function test(){
8         console.log("test function");
9     }
10     test()


申明了函数后无论在哪都能被调用,这是因为函数被整体提升到了前面去了,这与变量提升有些不同,变量只是申明被提升到了前面,而函数是整体被提升到了前面。

碰到的坑

1     var test = function(){
2         console.log("test");
3     }
4     function test(){
5         console.log("test function");
6     }
7     test();//输出 test


1     function test(){
2         console.log("test function");
3     }
4     var test = function(){
5         console.log("test");
6     }
7     test();//还是输出 test


WTF?两次都是输出test,我开始也是一脸萌比了。其实了解后才恍然大悟。

第一种情况提升后

1     var test //我被提升了
2     function test(){
3         console.log("test function");  //我也被提升到这里来了哈哈
4     }
5     //---------------------上面是提升区-----------------------------------
6         test = function(){
7         console.log("test");
8     }
9     // function test(){
10     //     console.log("test function");  //我被提升到上面去了
11     // }
12         test();//输出 test


只要申明了变量和定义函数开始都会被按照顺序提升到最前面,然后按照顺序执行代码,首先输出 test function 然后被test覆盖了,所以最后输出了test

第二种情况提升后

1     function test(){
2         console.log("test function");  //我被提升到上面去了
3     }
4     var test;
5     //---------------------上面是提升区-----------------------------------
6     // function test(){
7     //     console.log("test function");  //我被提升到上面去了
8     // }
9     test = function(){     //我的申明被提升了
10         console.log("test");
11     }
12     test();//还是输出 test


提升后按照顺序执行,发现test function还是被test覆盖了,最后还是输出了test

最后一种情况提升前

1     test(); //输出test function
2     function test(){
3         console.log("test function");
4     }
5     var test = function(){
6         console.log("test");
7     }


提升后

1     function test(){
2         console.log("test function");
3     }
4     var test;
5     //---------------------上面是提升区-----------------------------------
6     test(); //输出test function
7     // function test(){
8     //     console.log("test function");  //我被全部提升到上面去了
9     // }
10         test = function(){
11         console.log("test");
12     }


这个第6行调用输出 test function 。为什么是这个结果呢?代码按照顺序执行,第四行虽然声明提上来了,但是没有值,第六行就已经输出来了,不存在覆盖的情况。直接输出了test function。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: