Looking through the jQuery source in the function now()
I see the following:
function now(){
return +new Date;
}
I've never seen the plus operator prepended to the new operator like this. What does it do?
function now(){
return +new Date;
}
This function means the developer is clever.
function now(){
return (new Date()).getTime();
}
This function means, get the current time in milliseconds since 1970. And the developer has some mercy for those who wish to understand WTF is going on.
Nicolás and Brian are right, but if you're curious about how it works, +new Date();
is equivalent to (new Date()).valueOf();
, because the unary +
operator gets the value of its operand expression, and then converts it ToNumber
.
You could add a valueOf
method on any object and use the unary + operator to return a numeric representation of your object, e.g.:
var productX = {
valueOf : function () {
return 500; // some "meaningful" number
}
};
var cost = +productX; // 500
I think the unary plus operator applied to anything would cause it to be converted into a number.
It converts the Date()
into an integer, giving you the current number of milliseconds since January 1, 1970.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With