为什么下面的代码运行良好? const 是常量的缩写,它的值永远不应该改变
const myHeading = document.getElementById("myHeading") ;
myHeading.addEventListener("click", () => {
myHeading.style.color("red") ;
}) ;
最佳答案
使用 const
声明的变量永远不能重新分配 - 如果您看到
const someVarName = <something>
禁止的是左侧带有 someVarName
的后续语句:
someVarName = <something else> // TypeError: Assignment to constant variable.
它并不禁止突变,例如
someVarName.foo = 'foo';
您不会将 myHeading
重新分配给其他内容,因此没有问题。
关于javascript - 将 document.getElementById() 存储在 const 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55547140/