javascript - 在 ES6 中使用相同的参数名称作为其默认参数

标签 javascript ecmascript-6 babeljs

这段 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 规范是这样说的:

  1. 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/

相关文章:

javascript - 在 JavaScript (ES6) 中合并数组以形成数组数组

javascript - ESLint 规则通过创建同名的 const 来防止覆盖函数(尤其是在赋值期间)

vue.js - 在 Vue-CLI 项目中,Babel 没有为 IE11 转译 block vendor

JavaScript 打字机脚本不工作

javascript - 围绕箭头主体的意外 block 语句 ESlint

javascript - SceneJS 对比 Three.JS 对比其他

javascript - React-loadable 仅从相对路径获取 block

node.js - 使用文件的绝对路径时,babel-node 失败

javascript - 通过轮询检查 Capybara 中是否存在 html 标签的特定属性

javascript - 为什么这个 FileReader onload 没有触发?