Using same argument name as its default parameter

2020-03-01 20:29发布

问题:

This ES6 code:

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

Transpiled to:

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

Gives error:

    return log();
           ^
TypeError: log is not a function

The problem is this line:

const parent = (log = log) => log();

Because the argument name is same as its default parameter.

This works:

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

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

回答1:

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

The ES6 spec is saying to that point:

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

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.

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.

Simple example:

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

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