经典的 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)。
运行结果如下:


浙公网安备 33010602011771号