如何在ES6上声明一个`let`变量? [英] How can I check if a `let` variable has been declared on ES6?
问题描述
let
声明附加到块范围,但没有初始化,直到它们出现在块 所以:
console.log(a); // undefined
console.log(b); // ReferenceError!
var a;
let b;
所以似乎这里没有应用起重。
问题
如果是,如何安全地检查变量是否已经声明?
NB - 我看到的选项是try / catch,当然总是把 let
变量先放在范围。但仍然是我的问题仍然是
似乎在这里不适用起重。
不完全是。变量仍然覆盖完整的范围,当输入范围时就会创建绑定,就像使用 var
s。
但是你是对的,与 var
相反,它不是立即用 undefined
初始化,只有当 let
语句被评估。从范围顶部到那里的区域称为时间死区 - 标识符是绑定的,但在使用时总是会抛出一个 ReferenceError
。
如何安全地检查变量是否已经声明?
你不能,就像你不能为 var
s 1 。你不需要这个。
1:让我们忽略在这里成为全局对象的属性的全局变量 2 br>
2: var
/ function
/ function *
-declared变量,我的意思是。词法绑定( let
, const
)确实不会成为全局属性。
Unlike traditional var-declared variables, which are attached to the entire enclosing, function scope regardless of where they appear — let
declarations attach to the block scope but are not initialized until they appear in the block
So :
console.log( a ); // undefined
console.log( b ); // ReferenceError!
var a;
let b;
So it seems that hoisting is not applied here.
Question
If so , how can I safely check if the variable has been declared ?
NB - The option I see is try/catch and of course always put the let
variables first at scope. but still my question remains
it seems that hoisting is not applied here.
Not exactly. The variable still covers the complete scope, the binding is created when the scope is entered just like with var
s.
But you're right, in contrast to var
s it is not initialised with undefined
immediately, only when the let
statement is evaluated. The area from the top of the scope to there is called temporal dead zone - the identifier is bound, but will always throw a ReferenceError
when used.
How can I safely check if the variable has been declared?
You cannot, just as you cannot for var
s1. You don't need this anyway.
1: Let's ignore global variables2 that become properties of the global object here.
2: var
/function
/function*
-declared variables, I mean. Lexical bindings (let
, const
) indeed don't become global properties.
这篇关于如何在ES6上声明一个`let`变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!