gpt4 book ai didi

javascript - 为什么全局let变量没有添加到浏览器的window对象中?

转载 作者:行者123 更新时间:2023-12-02 21:41:50 24 4
gpt4 key购买 nike

考虑下面我在 Chrome 浏览器控制台中运行的代码:

var x = "hello";

let foo = function(){
console.log("hi");
};

console.log(x); // hello
console.log(foo()); //hi

console.log(window.x); // hello
console.log(window.foo()); // Error

如果我使用var foo =...而不是let foo = ..那么这就会起作用。为什么 ?

最佳答案

作者:design :

let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter is initialized to a value only when a parser evaluates it (see below).

Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

关于javascript - 为什么全局let变量没有添加到浏览器的window对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60346763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com