如何在ES6上声明一个`let`变量? [英] How can I check if a `let` variable has been declared on ES6?

查看:150
本文介绍了如何在ES6上声明一个`let`变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与传统的var声明的变量不同,传统的变量声明变量附加到整个封闭的函数范围,无论它们出现在哪里 - 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 vars.

But you're right, in contrast to vars 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 vars1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆