JS变量的默认参数值:为什么标识符必须不同? [英] JS default argument value from variable: why must identifier be different?
问题描述
使用具有相同名称的变量分配默认值会引发引用错误:
var a = 'adef';
var x = (a=a) => console.log(a);
x();
=> "ReferenceError: a is not defined"
但这很好:
var other = 'otherdef';
var x = (a=other) => console.log(a);
x();
=> "otherdef"
我的假设是将外部范围中的a
的值分配给新范围.
我尝试使用const
代替var
,并使用class
/function
代替箭头功能,但结果始终相同(在chrome 63和node 6中测试). >
我感觉到问题是a
在赋值期间被吊起",因此赋值是指新的"a"(存在但未定义)...
此行为的目的是允许将一个参数默认初始化为另一个参数的值,例如:
var a = 2;
var x = (a, b = a) => console.log(a, b);
x(42); // 42 42
使特例a = a
的工作方式有所不同 可以完成,但这将使重构使用此行为的函数更加困难(如果没有此功能,您将无法重命名参数a
还重命名它所依赖的变量.
Assigning a default value using a variable with the same name throw a reference error:
var a = 'adef';
var x = (a=a) => console.log(a);
x();
=> "ReferenceError: a is not defined"
But this is fine:
var other = 'otherdef';
var x = (a=other) => console.log(a);
x();
=> "otherdef"
My assumption was that the value of a
in the outer scope would be assigned to the new scope.
I have tried using const
instead of var
, and class
/function
instead of an arrow-function, but the result is always the same (tested in chrome 63 and node 6).
I have a feeling the issue is that a
is 'hoisted' during assignment and so the assignment is referring to the new 'a' (which exists but is undefined)...
The purpose of this behavior is to allow a parameter to be default-initialized to the value of another parameter, e.g:
var a = 2;
var x = (a, b = a) => console.log(a, b);
x(42); // 42 42
Making the special case a = a
work differently could be done but that would make it harder to refactor functions that use this behavior (you wouldn't be able to rename the parameter a
without also renaming the variable that it depends on).
这篇关于JS变量的默认参数值:为什么标识符必须不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!