Javascript如何声明函数参数? [英] How does Javascript declare function parameters?
问题描述
function func(x = y, y = 2) {
return [x, y];
}
func(); // ReferenceError: y is not defined
func(1); // [1, 2]
如上面的代码所示,函数中有一个隐藏的TDZ参数范围,解释了为什么下面的代码失败:
As the code above implied, there is a hidden TDZ in the function parameters scope, which explains why the code below fails:
function func(arg) {
let arg = 1; // SyntaxError: Identifier 'arg' has already been declared
}
所以函数参数应该用声明
,但让我困惑的是:
So function parameters should be declared with let
, but what confused me is :
function func(arg) {
var arg = 1;
console.log(arg); // 1
}
此代码工作正常。
为什么你可以使用 var
重新声明变量? Javascript如何声明函数参数?
Why you can redeclare variables using var
? How does Javascript declare function parameters?
编辑:
我确切知道你不能使用let来重新声明一个变量。这里的问题是,如果使用 let
声明函数参数,那么:
edit:
I know exactly you can't use let to redeclare a variable. The question here is if function parameters is declared using let
, so:
function func(arg) {
var arg = 1;
}
如下:
let arg; // arg parameter declares here
var arg = 1; // func body
为什么这可以无异常地运行?
and why this can run without an exception?
推荐答案
函数参数范围内有隐藏的TDZ
there is a hidden TDZ in the function parameters scope
确实如此。有关更多示例,请查看此处。
Yes indeed. Have a look here for some more examples.
Javascript如何声明函数参数?
How does Javascript declare function parameters?
作为参数 - 参见这里逐步解释。它们既不与 let
相同,也不与 var
相同,它们有自己的语义。引入默认初始化程序的ES6给予它们与让
相同的TDZ限制,以捕获更多程序员错误。
As parameters - see here for a step-by-step explanation. They're neither the same as let
nor the same as var
, they have their own semantics. ES6, which introduced default initialisers, gave them the same TDZ limitations as in let
to catch more programmer mistakes.
为什么你可以使用
var
重新声明变量?
因为在ES5之前,重新声明变量不是错误条件,并且需要保留此行为以不破坏Web。它只能用于新功能,如让
和 const
- 或使用默认初始化程序的参数列表,尝试 function x(bar,bar){}
vs function x(bar,bar = 1){}
。
Because until ES5, redeclaring a variable was not an error condition, and this behaviour needed to be preserved to not break the web. It could only be introduced for new features, like let
and const
- or argument lists that use default initialisers, try function x(bar, bar) {}
vs function x(bar, bar=1){}
.
这篇关于Javascript如何声明函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!