Using same argument name as its default parameter in ES6

前端 未结 1 1354
感动是毒
感动是毒 2021-01-05 02:23

This ES6 code:

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

Transpiled to:

v         


        
相关标签:
1条回答
  • 2021-01-05 02:59

    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 }
    }
    
    0 讨论(0)
提交回复
热议问题