首页 > 解决方案 > 为什么在我的 Rails 应用程序中未定义预编译的 vanilla JS 脚本中的 const,但在我删除 const 关键字时有效

问题描述

我的 assets/javascripts 目录中有一个 vanilla JS 文件,并window.addEventListener(DOMContentLoaded)在所述文件中放置了一个基本函数。

但是,在事件侦听器的回调函数中const divs = document.querySelectorAll('div');,当我在浏览器/控制台中查看该页面时,div没有定义。

我删除了const关键字,但保留了其他所有内容,突然间,它起作用了。

为什么?

标签: javascriptruby-on-rails

解决方案


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只能在函数内部访问,因为它是函数范围,而不是全局的并且它在另一个块内。


推荐阅读