问题
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)...
回答1:
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).
来源:https://stackoverflow.com/questions/47813168/js-default-argument-value-from-variable-why-must-identifier-be-different