What does the '+new' mean in JavaScript?
Looking through the jQuery source in the function now()
I see the f开发者_开发问答ollowing:
function now(){
return +new Date;
}
I've never seen the plus operator prepended to the new operator like this. What does it do?
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.
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.
精彩评论