参数不会被提升并会达到时间死区?

时间:2018-06-12 02:15:49

标签: javascript



function bar(x=y, y=2) {
    return [x, y];
}

bar();//uncaught reference: y is not defined




我无法理解为什么上面的代码会遇到异常。如果来自其他语言它是有意义的,因为程序流很重要,我们不能引用y,因为y尚未创建,并且会导致编译错误。但是这是JS,x和y都应该首先被提升,这样的引用不应该抛出异常。我希望伪代码类似于下面的代码?



x=y

var x;
var y;

console.log(x,y); //undefined undefined (which is fine as no value but instead of throwing exception)




更新



function bar() {
    var x = arguments.length >= 1 ? arguments[0] : y;
    {
        var y = arguments.length >= 2 ? arguments[1] : 2;

        return [x, y];
    }
}

console.log(bar());//[undefined, 2]




1 个答案:

答案 0 :(得分:8)

你的假设是错的,他们并没有像那样被吊起来。它更像是:

function bar() {
    let x = arguments.length >= 1 ? arguments[0] : y;
    {
        let y = arguments.length >= 2 ? arguments[1] : 2;

        return [x, y];
    }
}

每个变量默认值的范围仅包括左侧的变量,而不包括右侧的变量。