Javascript ES6 'let' 和 'var' - 函数内部的意外行为,参数名称与重新声明的变量匹配 [英] Javascript ES6 'let' and 'var' - unexpected behavior inside function with argument name matching redeclared variable

查看:52
本文介绍了Javascript ES6 'let' 和 'var' - 函数内部的意外行为,参数名称与重新声明的变量匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,这不是现有 var 与 let 范围的重复.我知道 var 和 let 声明和差异的范围.

Please note this is not duplicate of existing var vs let scope. I'm aware of the scope of var and let declarations and differences.

但在下面的场景中,我无法证明我对 letvar 差异的理解.

But below scenario I could not justify with the understanding I had with let and var difference.

在下面的代码中,函数 foo 接受名称为 'x' 的参数,该参数具有隐式 let 范围 - 因为我无法使用 let<重新声明相同的变量名称/code> 在该函数中(取消注释函数 foo 中的最后一行会抛出 JS 错误)

In the below code, function foo accepts argument by name 'x' which has implicit let scope - as I cannot redeclare same variable name using let inside that function (uncommenting last line in function foo will throw JS error)

"use strict";

function foo(x) {
    console.log('Inside function x:', x);
    var x = 30; // 'x' redeclared overwriting argument/parameter 'x'
    console.log('Redeclared x:', x);
    // let x = 400; // uncommenting this line throws error even if you remove 'var x = 30;'
}

foo(100);
// global
let y = 100;
console.log('y:', y);
// var y = 300;

注释掉两行执行上面的代码效果很好,可以看到输出为:

Executing the above code with two lines commented out works perfectly, and you can see the output as:

Inside function x: 100      index.js:4 
Redeclared x: 30            index.js:6
y: 100                      index.js:13

取消注释最后一行 //var y = 300; 会抛出错误.

Uncommenting last line // var y = 300; will throw error.

问题:为什么在函数 foo 中使用 'var' 重新声明 'x' 有效,但在重新声明 'y' 时会抛出错误使用 'var'

Question is: Why redeclaring 'x' using 'var' inside function foo works but throws error when 'y' is redeclared in the global scope using 'var'

推荐答案

var 声明语法是该语言的原创,并且具有相当宽松的规则.letconst 声明更新且更严格.你不能用 letconst 重新声明变量,无论它们最初是如何声明的.如果一个变量是用 letconst 声明的,那么后续的 var 声明也是一个错误.

The var declaration syntax is original to the language, and has fairly permissive rules. The let and const declarations are newer and more strict. You cannot re-declare variables with let or const no matter how they were declared in the first place. And if a variable is declared with let or const, a subsequent var declaration is also an error.

通过letconst 的声明将不允许在声明之前引用变量;这就是为什么您会收到第一个示例中提到的错误.换句话说,

Declarations via let and const will not allow references to the variables before the declaration; that's why you get the error mentioned in your first example. In other words,

console.log(x);
let x = 0;

是一个错误,因为 x 在声明之前被引用.

is an error because x is referenced before the declaration.

这篇关于Javascript ES6 'let' 和 'var' - 函数内部的意外行为,参数名称与重新声明的变量匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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