在下面的代码中:
(function (){
function test(){};//"function"
var test;//"undefined"
var printTest = typeof test;
document.write(printTest);
})();
printTest 将显示“函数”而不是“未定义”,这是有道理的,因为根据我的理解,任何变量声明总是“提升”到执行上下文的顶部(在本例中是函数执行上下文)这使得函数声明“test()”是稍后出现在当前执行上下文中的那个。现在考虑这段代码,我实际上为 var 声明“var test =1”分配了一个值。
(function (){
function test(){};
var test=1;//assign value to a variable here
var printTest = typeof test;
document.write(printTest);
})();
然后 printTest 现在显示“数字”,这意味着执行上下文现在保持不同的顺序。有人可以解释这里实际发生了什么吗?
最佳答案
提升将实际赋值与变量声明分开。它真正在做的是:
(function (){
var test, printTest;
test = function (){};
test = 1;//assign value to a variable here
printTest = typeof test;
document.write(printTest);
})();
关于javascript - Function Expression 本身不能将 Name 赋值给另一个 Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6318835/