关于 js 函数默认值的问题

下面这两种写法为什么会产生两种不同的结果?求大佬详细解答.... 个人觉得是跟函数参数的块级作用域有关.....但是理解起来还是怪怪的,而且用 chrome debugger 来查看也觉得怪怪的,为啥最后那个输入 x,是根据 Block 来输出的?万分感谢~

function test (x, y = function t () { x = 2 }) {
  var x
  y()
  console.log(x) // undefined
}
test()
function test (x, y = function t () { x = 2 }) {
  // var x
  y()
  console.log(x) // 2
}
debugger
test()
阅读 1.8k
2 个回答

9.2.12 FunctionDeclarationInstantiation

If default value parameter initializers exist, a second Environment Record is created for the body declarations.

如果存在函数默认值,那么会为函数体部分创建第二个环境记录,这个第二个环境是在函数默认值之下的。
类似于:

// ES6
function foo(x, y = function() { x = 2; }) {
  var x = 3;
  y(); // is `x` shared?
  console.log(x); // no, still 3, not 2
}
 
// Compiled to ES5
function foo(x, y) {
  // Setup defaults.
  if (typeof y == 'undefined') {
    y = function() { x = 2; }; // now clearly see that it updates `x` from params
  }
 
  return function() {
    var x = 3; // now clearly see that this `x` is from inner scope
    y();
    console.log(x);
  }.apply(this, arguments);
}

代码来自 es6-notes-default-values-of-parameters

  1. 第一种情况,var x 覆盖了参数变量x;
  2. 第二种情况 很简单,调用test()时,没有传递y,就形成了一个闭包。y函数依然能够访问局部变量x,甚至还能修改它。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题