仅在 Safari 中:ReferenceError 找不到变量
Only in Safari: ReferenceError Can't find variable
我的很多脚本都是这样的:
if (...) {
const myvariable1 = document.querySelector('.class-1');
const myvariable2 = document.querySelector('.class-2');
function someFunction() {
// Do something with myvariable1 or myvariable2
}
someFunction();
}
它们在 Chrome、Firefox、Edge 和 Opera 上运行良好,但在 Safari 上出现错误:
ReferenceError: Can't find variable myvariable1
解决方法
如果我在 if 语句之前声明常量,代码就可以工作...
const myvariable1 = document.querySelector('.class-1');
const myvariable2 = document.querySelector('.class-2');
if (...) {
function someFunction() {
// Do something with myvariable1 or myvariable2
}
someFunction();
}
...但我不明白为什么,也不知道如何使常量全局可用。
也许有人可以向我解释 Safari-only-behavior。
这种奇怪的行为在 Block-level functions in non-strict code - MSN 中有解释。
启用strict mode将解决这个问题。
我的很多脚本都是这样的:
if (...) {
const myvariable1 = document.querySelector('.class-1');
const myvariable2 = document.querySelector('.class-2');
function someFunction() {
// Do something with myvariable1 or myvariable2
}
someFunction();
}
它们在 Chrome、Firefox、Edge 和 Opera 上运行良好,但在 Safari 上出现错误:
ReferenceError: Can't find variable myvariable1
解决方法
如果我在 if 语句之前声明常量,代码就可以工作...
const myvariable1 = document.querySelector('.class-1');
const myvariable2 = document.querySelector('.class-2');
if (...) {
function someFunction() {
// Do something with myvariable1 or myvariable2
}
someFunction();
}
...但我不明白为什么,也不知道如何使常量全局可用。
也许有人可以向我解释 Safari-only-behavior。
这种奇怪的行为在 Block-level functions in non-strict code - MSN 中有解释。
启用strict mode将解决这个问题。