1

Right now I'm reading through You Don't Know JS Types & Grammar Ch 4 where I came across this example on coercion. 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
}

I don't get why things aren't off by one. Since var i starts out at 2, when it hits a == 2 shouldn't 3 be returned and then shouldn't 4 be returned when a == 3 is run?

4

2 回答 2

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
}

于 2016-09-12T21:17:46.657 回答
1

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

于 2016-09-12T21:16:44.390 回答