JS default argument value from variable: why must identifier be different? [duplicate]

萝らか妹 提交于 2019-12-01 02:58:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!