javascript - 请教,一个 JS 中关于函数提升的问题?
代言
代言 2017-06-12 09:30:06
0
3
656

如下代码:

function a() {
    console.log('1')
}    

(function() {
    console.log(a);
    if(1) {
        function a() {
            console.log('2');
        }
    }
})()

运行之后,输出的是undefined。

而去掉 if 条件之后,输出的又是第二个 a 函数

function a() {
    console.log('1')
}    

(function() {
    console.log(a);

    // if(1) {
        function a() {
            console.log(2);
        }
    // }
})()

知道函数有提升,第二段代码,第二个 a 函数会提升到 console.log(a) 这句代码之前,所以运行输出 第二个 a 函数。
可是第一段代码,就搞不明白为啥会输出 undefined 了。

代言
代言

全部回复(3)
代言

条件式函数声明跟函数表达式的处理方式一样。因此,条件式函数声明丧失了函数声明提升的特性。

参考网址:/q/10...

刘奇

在 if else 语句中使用 function 关键字进行函数声明时,变量的提升在不同浏览器中是不一样的。只是这里刚好是提升了个变量的声明,去掉了 if else 就成了单纯的函数作用域。

function a() {
    console.log('1')
}    

(function() {
    var a;
    console.log(a);
    if(1) {
        a = function a() {
            console.log('2');
        }
    }
})()
学习ing

你的IIFE中的

 if(1) {
  a = function a() {
    console.log('2')
  }
} 

是个函数表达式,而不是函数声明,当 去掉if的时候是函数声明,没有去掉if ,conosle.log(a),a表示未定义的变量a,参考https://developer.mozilla.org...

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板