这段 ES6 代码:
const log = () => console.log('hi');
const parent = (log = log) => log();
parent();
转译为:
var log = function log() {
return console.log('hi');
};
var parent = function parent() {
var log = arguments.length <= 0 || arguments[0] === undefined ? log : arguments[0];
return log();
};
parent();
给出错误:
return log();
^
TypeError: log is not a function
问题是这一行:
const parent = (log = log) => log();
因为参数名称与其默认参数相同。
这个有效:
const log = () => console.log('hi');
const parent = (logNow = log) => logNow();
parent();
这是 Babel 中的错误还是规范本身不允许这样做?
最佳答案
这似乎是 ES6 的预期行为。 在 Chrome 控制台上测试,也有错误。
ES6 规范是这样说的:
- Let parameterNames be the BoundNames of formals. http://www.ecma-international.org/ecma-262/6.0/#sec-functiondeclarationinstantiation
这意味着当你创建函数时,ES6 会做与 babel 基本相同的事情,它将在新的上下文中管理参数的分配。
在javascript中,当你在一个封闭的作用域中创建一个变量a
时,全局的a
就不能再被访问了,因为JS会把a
code> 来自最近的可能范围,在 AST 中。
简单的例子:
var a = 1;
function test() {
// creates the variable a, and try to assign a value to it,
// because `a` is now available in the scope itself, it will take value of a in the inner scope, not the outer scope one
var a = a;
console.log(a)
}
test() // undefined
为什么不取外层a的值,然后赋值给内层a,是因为提升,基本上是这样做的:
function test() {
var a; // the address for the variable is reserved at compile time
a = a; // run-time assignment
}
它获取函数的所有变量声明并将其提升到函数的开头。
这就是为什么像这样的东西会起作用的原因:
function hoistingTest(n, m = 2) {
// return immediately
return multi(n);
// This declaration will be hoisted to the begin of the body
function multi(n) { return m * n }
}
关于javascript - 在 ES6 中使用相同的参数名称作为其默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38303828/