【发布时间】:2019-02-16 22:20:43
【问题描述】:
如果我打开 JS 控制台并写:
let foo;
之后:
let foo = "bar"
控制台显示(正确)
Uncaught SyntaxError: Identifier 'foo' has already been declared
现在...有时我需要在现有脚本中注入我的代码,而我没有工具来确定是否已经定义了 let 变量。
我尝试使用此代码,但 JS 范围和逻辑存在明显问题....(注释代码)
let foo; // Gloabl variable empty declare in a code far, far away
console.log(foo); // undefined
console.log(typeof foo === "undefined"); // test that determinate if condition is true
if(typeof foo === "undefined"){
let foo = "test";
console.log(foo); // return "test" this means that foo as a local scope only inside this if...
}
console.log(foo); // return undefined not test!
// and .. if I try to double declaration...
let foo = "bar"; //error!
所以...如何防止双重“让”声明? / 如何判断一个 let var 是否被定义(声明?)
附言 使用“var”一切正常!!!
【问题讨论】:
-
用
var声明的变量具有函数作用域,并且被提升,不像let/const -
“现有脚本”是你写的?
-
请注意,这是一个语法错误,而不是运行时错误。你能解释一下你的
sometimes I need to inject my code inside an existing script吗? -
也许你可以把你的代码放在一个 iife 中,这样它就不会和其他的共享相同的范围?
-
@JNF 我认为这不是我自己的代码。
标签: javascript variables ecmascript-6 let