[英]Javascript ES6 'let' and 'var' - unexpected behavior inside function with argument name matching redeclared variable
Please note this is not duplicate of existing var vs let scope. 请注意,这不是现有var vs let范围的重复项。 I'm aware of the scope of var and let declarations and differences. 我知道var的范围,并允许声明和区别。
But below scenario I could not justify with the understanding I had with let
and var
difference. 但是在以下情况下,我无法用let
和var
差异来证明我的理解。
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) 在下面的代码中,函数foo
接受具有隐式let
范围的名称“ x”的参数-因为我无法在该函数内部使用let
重新声明相同的变量名(取消注释函数foo
最后一行会引发JS错误)
"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
Uncommenting last line // var y = 300;
最后一行取消注释// var y = 300;
will throw error. 会抛出错误。
Question is : Why redeclaring 'x' using ' var
' inside function foo
works but throws error when 'y' is redeclared in the global scope using ' var
' 问题是 :为什么在函数foo
使用' var
'重新声明'x'可以工作,但是在全局范围内使用' var
'重新声明'y'时却抛出错误
The var
declaration syntax is original to the language, and has fairly permissive rules. var
声明语法是该语言的原始语法,并且具有相当宽松的规则。 The let
and const
declarations are newer and more strict. let
和const
声明是更新的和更严格的。 You cannot re-declare variables with let
or const
no matter how they were declared in the first place. 无论最初如何声明,都不能使用let
或const
重新声明变量。 And if a variable is declared with let
or const
, a subsequent var
declaration is also an error. 而且,如果使用let
或const
声明变量,则后续的var
声明也是错误。
Declarations via let
and const
will not allow references to the variables before the declaration; 通过let
和const
进行的声明将不允许在声明之前引用变量; that's why you get the error mentioned in your first example. 这就是为什么您遇到第一个示例中提到的错误的原因。 In other words, 换一种说法,
console.log(x);
let x = 0;
is an error because x
is referenced before the declaration. 是一个错误,因为在声明之前引用了x
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.