使用var vs.let/const进行块级变量重新声明 [英] Block-level variable redeclaration with var vs. let/const

查看:55
本文介绍了使用var vs.let/const进行块级变量重新声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下示例:

var number = 10
{
   var number = 42
}
console.log(number) // 42

为什么第4行不抛出未捕获的SyntaxError:标识符'number'已经被声明?由于块作用域,它可以与 let / const 一起使用(尽管输出当然是 10 而不是 42 ),但如何与 var 一起使用?

Why does line 4 not throw an Uncaught SyntaxError: Identifier 'number' has already been declared? It works with let / const because of block scoping (although the output is, of course, 10 not 42), but how come it works with var?

将此与以下代码进行比较,该代码可与 var 一起使用:

Compare this to the following, which works with var:

var number = 10
var number = 42
console.log(number) // 42

但不包含 let :

let number = 10
let number = 42 // SyntaxError
console.log(number)

为什么给 var 提供免费通行证"?使用 var 时,是否必须将 number 属性重新分配给窗口对象?

Why is var given a "free pass"? Does it have to do with the number property being reassigned to the window object when var is used?

推荐答案

您甚至可以在严格模式下在JavaScript中重新声明 var 变量.

You are allowed to redeclare var variables in JavaScript, even in strict mode.

var 声明的变量的范围是其当前的执行上下文,它是封闭函数,或者对于任何函数外部声明的变量,都是全局变量.如果您重新声明一个JavaScript变量,它将不会丢失其值.

The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

'use strict'
var someVar = 'Hello';
var someVar = 2 + 2;
console.log(someVar);

这篇关于使用var vs.let/const进行块级变量重新声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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