执行上下文两次声明名称

execution context declared name twice?

本文关键字:两次 声明 上下文 执行      更新时间:2023-09-26

我正在研究Javascript中的执行上下文。但我不明白为什么"函数foo"不会被"var foo"重写。我希望有人能解释一下,感谢您的回复。

函数ace(){

console.log(typeof foo); // function pointer
console.log(typeof bar); // undefined
var foo = 'hello',
    bar = function() {
        return 'world';
    };
function foo() {
    return 'hello';
}
 var foo = 'hello';

}

ace();

为什么"函数foo"不会被"var foo"重写。

foofoo被重新定义的行被重写

function ace() {
  console.log(typeof foo); // function pointer
  console.log(typeof bar); // undefined
  var foo = 'hello',
    bar = function() {
      return 'world';
    };
  function foo() {
    return 'hello';
  }
  var foo = 'hello';
  console.log(foo);
  try {
    foo()
  } catch(e) {
    console.log("catch:", e.message)
  }
}
ace();

但我不明白为什么"函数foo"不会被"var foo"重写。

var声明不会覆盖函数声明。它们都声明了相同的变量,并且由于函数声明,它是用函数初始化的。只有赋值才会覆盖该值。

如果你考虑吊装,你的脚本将表现得像

function ace() {
    var foo, bar;
    var foo = function() {
        return 'hello';
    }
    var foo;
    console.log(typeof foo); // function
    console.log(typeof bar); // undefined
    foo = 'hello';
    bar = function() {
        return 'world';
    };
    console.log(typeof foo); // string
    foo = 'hello';
}
ace();