javascript - 为什么在我的 Rails 应用程序中未定义预编译的 vanilla JS 脚本中的 const,但在我删除 const 关键字时有效
问题描述
我的 assets/javascripts 目录中有一个 vanilla JS 文件,并window.addEventListener(DOMContentLoaded)
在所述文件中放置了一个基本函数。
但是,在事件侦听器的回调函数中const divs = document.querySelectorAll('div');
,当我在浏览器/控制台中查看该页面时,div
没有定义。
我删除了const
关键字,但保留了其他所有内容,突然间,它起作用了。
为什么?
解决方案
let
并且const
是所谓的块范围。这意味着它们只能从它们定义的“区域”和子部分中访问。基本上,您正在关注大括号。在下面的示例中,我将使用let
代替const
,以便我可以更改值。
var x = 10; // this is global scope and can be seen everywhere
{
var x = 5; // this is the same x as above because it is global
console.log(x); // prints 5
}
console.log(x); // still prints 5 because we changed the global x
function test1() {
var x = "test1"; // this is inside a function so it is function scoped
console.log(x); // prints "test1";
}
test1(); // prints "Test1" from inside the function
console.log(x); // still prints 5 because the global x is separate from the inside function x
如果我们采用相同的代码并将其更改var
为 a let
,就会发生这种情况
let x = 10; // this is global scope and can be seen everywhere
{
let x = 5; // this is inside brackets, so its a new block. This x is separate from the global x
console.log(x); // prints 5
}
console.log(x); // prints 10 because we are global again
function test1() {
let x = "test1"; // this is inside a function so it is function scoped
console.log(x); // prints "test1";
}
test1(); // prints "Test1" from inside the function
console.log(x); // still prints 10 because we are still at the global block
我猜您正在事件侦听器中使用 const div,但尝试在另一点访问该变量:
window.addEventListener("DOMContentLoaded", function() {
const divs = document.querySelectorAll('div');
console.log(divs); // prints NodeList [<div>] …
});
console.log(divs); // error
发生错误是因为divs
只能在函数内部访问,因为它是函数范围,而不是全局的并且它在另一个块内。
推荐阅读
- exception - vertx IllegalArgumentException: No message codec for type - 如何为自定义类型创建消费者
- awk - 如何使用 awk 在行组中添加缺失的行
- c# - 拉普拉斯使用c#我哪里出错了?
- openlayers - Openlayers:确定是否设置了 precompose 处理程序
- c# - 是否可以在 WCF wsdl 中包含一个 DataContract 类,而该类不属于任何 OperationContract?
- airflow - 在 Airflow 中使用 ds_add 和宏
- javascript - ASP.NET 根据 SQL 查询结果更改 Href
- android - 找不到类“android.support.test.runner.AndroidJUnitRunner”
- python - update_or_create 在外键的两个实例上覆盖字段对象
- date - 将 SAS 列转换为日期格式