使用相同的参数名称作为ES6中的默认参数 [英] Using same argument name as its default parameter in ES6

查看:83
本文介绍了使用相同的参数名称作为ES6中的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此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();

因为参数名称与其默认参数相同。

Because the argument name is same as its default parameter.

这样做:

const log = () => console.log('hi');
const parent = (logNow = log) => logNow();
parent();

这是Babel中的错误还是规范本身不允许这样做?

Is this a bug in Babel or is this not allowed in the spec itself?

推荐答案

似乎这是ES6的预期行为。
在Chrome控制台上测试,也出现了错误。

Seems like this is the expected behavior of ES6. Tested on the Chrome console, also got an error.

ES6规范说到了这一点:

The ES6 spec is saying to that point:



  1. 让parameterNames成为形式的BoundNames。
    http://www.ecma-international.org/ ecma-262 / 6.0 / #sec-functiondeclarationinstantiation

  1. Let parameterNames be the BoundNames of formals. http://www.ecma-international.org/ecma-262/6.0/#sec-functiondeclarationinstantiation


这意味着您何时创建函数,ES6将像babel一样基本相同,它将在新的上下文中管理params的赋值。

This means when you create function, ES6 will do basically the same like babel is doing, it will manage the assignment of the params in the new context.

在javascript中,当你创建一个变量<封闭范围内的code> a ,全局 a ,不能再访问了,因为JS将采用来自最近可能范围的,在AST中。

In javascript, when you create a variable a in a closed scope, global a, cannot be accessed anymore, because JS will take the a from the nearest possible scope, in 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,是因为提升,基本上它是这样做的:

Why its not taking the value of outer a, and then assign it to the inner a, is because of hoisting, basically its doing this:

function test() {
  var a; // the address for the variable is reserved at compile time
  a = a; // run-time assignment 
}

它接受函数的所有变量声明和将它提升到函数的开头。

It takes all the variables declarations of a function and hoist it to the begin of the function.

这就是为什么这样的事情会起作用的原因:

This is the reason, why something like this will work:

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 }
}

这篇关于使用相同的参数名称作为ES6中的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆