函数表达式本身不能将名称分配给另一个值

Function Expression itself cannot assign Name to another Value

本文关键字:分配 另一个 表达式 不能 函数      更新时间:2023-09-26

在下面的代码中:

(function (){
    function test(){};//"function"
    var test;//"undefined"
    var printTest = typeof test;
    document.write(printTest);
})();

printTest将显示"function"而不是"undefined",这是有道理的,因为根据我的理解,任何变量声明都会被"提升"到执行上下文的顶部(在本例中是函数执行上下文)。这使得函数声明"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);
    })();

var test仅表示"任何称为测试的内容都应在本地确定范围"。它是未定义的,只是因为你没有给它赋值(除了你有function test(){};,这就是为什么你得到function而不是undefined)。

在第二个例子中,function test(){};仍然为它分配一个函数,但随后var test=1;1覆盖它。您在之后使用typeof,您将1分配给它,因此它会报告它是一个数字。

相关文章: