【JavaScript学习笔记】JavaScript踩坑(2)

一:函数参数作用域

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

函数体是函数参数的子域,即类似于下面这种结构:

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

当函数体内通过var再次声明x时,会将外层x覆盖;执行y()时,因为参数作用域在函数体的外面,无法访问内层变量,此时访问的是参数作用域的x,即将x由undefined赋值为2;而最终函数体内打印的是函数体内再次声明的变量x,值为3。

当函数体内的x变量前没有var时,此时修改的是参数作用域内的变量x,y()中将x修改为2,因此最终打印的值为2。

二:变量提升

(function (a) {
    console.log(a);//function: a
    var a = 10;
    console.log(a);//10
    function a() {}
})(100);

匿名函数的形参a的作用域在{}的外层,内层定义了函数a,并用var声明了变量a。其中var存在变量提升,function会在一开始先被扫描,并且function优先级高于var提升的变量,因此此时不是undefined而是function a。之后对a重新赋值,打印a=10。

三:truthiness

if (new Date()) {
  console.log('1');
}
if ({}) {
  console.log('2');
}

falsy为false,0,“”,null,undefined和NaN,此外都为真值。

猜你喜欢

转载自blog.csdn.net/orangecsy/article/details/79863386
今日推荐