function test() {
  console.log("out");
}
(function () {
  if (false) {
    function test() {
      console.log("in");
    }
  }
  test();
})();

  

 

 解析:可以这样理解,找到所有用function声明的变量,在环境中创建这些变量,但要注意的是,这些变量还没有被赋值,所以闭包中的test就变成了undefined,所以加上括号就会报错

如果在函数外面,在不同浏览器就会有不同的结果

/************函数变量重名*************/
function test() {
  console.log(1);
}
if (true) {
  function test() {
    console.log(3);
  }
} else {
  function test() {
    console.log(2);
  }
}
test(); //最新的浏览器输出3   safri输出2  在早期的一些过渡版本中输出1

//在函数内部只有一种答案,变量存在的情况也是一样

/**************变量重名**************/
var a = 10;
if (false) {
  var a = 11;
}
console.log(a); //10

var c = 10;
var c;
console.log(c); //10

var b = 10;
(function () {
  if (false) {
    var b = 11;
  }
  console.log(b); //undefined
})();

  执行过程:

var a;
var a;
a = 10;

var b;
b = 10;
(function () {
  var b;
  if (false) {
    b = 11;
  }
  console.log(b); //当前作用域,局部作用域的优先级是高于全局变量的,所以这里为undefined
})();

  知识点:

局部作用域的优先级是高于全局变量的,所以这里为undefined
js从来不会告诉你是否多次声明了同一个变量;遇到这种情况,他只会对后续声明视而不见,不过它会执行后续声明中的变量初始化。

 

posted on 2021-04-18 17:22  白不了的黑发  阅读(55)  评论(0编辑  收藏  举报