调用valueOf时的操作顺序

时间:2016-09-12 21:14:29

标签: javascript object event-loop coercion value-of

现在我正在阅读你不知道JS类型&语法第4章我在强迫中遇到了这个例子。 https://repl.it/D7w2

var i = 2;

Number.prototype.valueOf = function() {
    console.log("called"); //this logs twice
    return i++;
};

var a = new Number( 42 );

if (a == 2 && a == 3) {
    console.log( "Yep, this happened." ); //this is logged
}

我不明白为什么事情并没有被一个人拒之门外。因为var i从2开始,当它命中= = 2时,不应该返回3,然后在运行== 3时不应该返回?

2 个答案:

答案 0 :(得分:4)

不,因为你使用了后期增量。这将返回变量之前的值。

如果使用预增量++i,则增加变量并返回新值。



var i = 2;

Number.prototype.valueOf = function() {
    console.log("called"); //this logs twice
    return ++i;
};

var a = new Number( 42 );

if (a == 2 && a == 3) {
    console.log( "Yep, this happened." ); //this is logged
}




答案 1 :(得分:1)

a ++是后缀,它返回值然后递增。