The result of a piece of ES6 code after chrome execution is different from that after babel is compiled into ES5 code. If you want to know what the reason is, ask the boss to solve the puzzle.

first is the ES6 code

  var x = 1;
    function foo(x, y = function() { x = 2; }) {
      var x = 3;
      y();
      console.log(x);
    }
    
    foo();

when the above code runs on chrome, it prints 3.

when this ES6 code is compiled into ES5, it is shown in the following figure

var x = 1;
function foo(x) {
  var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
    x = 2;
  };

  var x = 3;
  y();
  console.log(x);
}

foo();

after the execution of this ES5 code, the print is 2

.

Why is it different? ask for advice.

Mar.21,2021

the key lies in the scope of the default parameters of the function:
https://www.jianshu.com/p/8fe.

Menu