【问题标题】:Isn't the variable declared outside with let global variable too?外面声明的变量不是也用 let 全局变量吗?
【发布时间】:2021-12-14 05:55:13
【问题描述】:

我正在尝试了解新的函数语法。

当我使用 let 声明变量“值”时,我得到一个错误

ReferenceError: 值未定义

但如果我使用 var 或不使用 var,则输出将作为测试打印。我假设“值”变量是全局变量,因为它是在外部定义的。

但是为什么它可以使用 var 而不是 let 虽然两者都是全局变量?

let value = "test";
    function getFunc() {
        // value = "test";
    
        let func = new Function('console.log(value)');
    
        return func;
    }
    
    getFunc()();

【问题讨论】:

  • 参见:varlet。两个文档都包含一个简单的示例。

标签: function global new-operator var referenceerror


【解决方案1】:

在顶层,letvar 不同,不会在全局对象上创建属性。

var foo = "Foo";  // globally scoped
let bar = "Bar"; // not allowed to be globally scoped

console.log(window.foo); // Foo
console.log(window.bar); // undefined

Reference

因此let 只能在{} 表示的封闭块内使用。

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2011-06-30
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 2011-10-13
    相关资源
    最近更新 更多