![](/img/trans.png)
[英]Assign a changed function to another variable and get different body with same name
[英]Assign a variable as a function parameter with the same name
我不明白为什么这是不正确的:
let a=5
a = a
//so there are no errors here. In the last statement javascript replaces the left side with a value, and that's it
现在如果我写这个:
let a=5
function hey(a=a){
return console.log(a)
}
hey()
这将返回未定义,因此参数 a=a 不会被评估为a=6
具有相同变量名称的用例是我想在脚本的开头创建一个带有变量的部分,并使用与稍后在函数中使用的名称相同的名称。
在第一个示例中,您有一个名为a
变量。 您可以将值分配给a
到a
。 这是没有意义的,但有可能。
在您的第二个示例中,您有两个不同的变量,它们都命名为a
,它们存在于不同的范围内。 在 function 声明中, a
指的是局部变量a
而不是全局变量a
。 当您尝试使用a
作为默认值时,它会读取本地范围a
,它是undefined
。
如果您想这样做,请使用不同的名称。 将它们组织在 object 中也可能是有意义的。
const default_values = { a: 5 }; function hey(a = default_values.a) { console.log(a); } hey();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.