一小段js代码的困惑,有关变量提升的问题

<script>


f = function () {
    return true;
};
g = function () {
    return true;
};

(function () {
    if (g() && []==![]){ //12行
        f=function f(){return false;};
        function g(){return true;}
    }
})();//16行


alert(g());
alert(f());
</script>

执行结果如下

clipboard.png

function g(){return true;}

这句理论上属于函数声明,应该会变量提升才对,12行为什么会产生g()不是函数的错误呢?

另外:最后的alert(g());
这句话和闭包中定义的function g(){return true;}有没有关系啊?

最后,闭包中f=function f(){return false;};这个f和外边的f有关系吗?
希望各位不吝赐教!

阅读 2.2k
4 个回答
  1. 声明提升,赋值又不会提升,所以 g 是 undefined 。
  2. 没关系
  3. 有关系

看眼这个吧。
不同浏览器貌似还不一样 ...

以下拷贝自上面的网站:

var hoisted = "foo" in this;
console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
if (false) {
  function foo(){ return 1; }
}

// In Chrome: 
// 'foo' name is hoisted. typeof foo is undefined
// 
// In Firefox:
// 'foo' name is hoisted. typeof foo is undefined
//
// In Edge:
// 'foo' name is not hoisted. typeof foo is undefined
// 
// In Safari:
// 'foo' name is hoisted. typeof foo is function

clipboard.png

不管条件是否成立都要进行变量提升,但是新版本浏览器只对函数进行声明

你把这段代码贴到IE8中执行再看看

新手上路,请多包涵

看起来就很复杂的样子

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题