经典的 JavaScript “陷阱”题---函数的参数默认作用域

先看代码,如下所示:

var x = 0;

function foo(x, y = function() { x = 3; console.log(x); }) {
  console.log('the first is:',x);
  var x = 2;
  y();
  console.log('the second is:',x);
}

foo(1);

console.log('the third is:',x);

默认参数有独立的作用域:默认参数函数 function() { x = 3; console.log(x); } 中的 x,优先指向「参数作用域的 x」(而非函数内部 var 声明的 x)。

 

运行结果如下:

image

posted @ 2026-03-23 10:48  chenlight  阅读(3)  评论(0)    收藏  举报