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?
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?
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.
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