与日期对象的乘法 - JavaScript [英] Multiplication with date object - javascript
问题描述
我发现这段代码 var timeStamp = 1 * new Date();
令我吃惊的是,自1970/01/01以来,它以毫秒为单位返回值。这相当于使用 .getTime()
方法!
引擎盖下发生什么?类型转换概念在这里工作,它基本上将新的Date()
值转换为毫秒?
发生什么事情?
简短版本:
由于它在数学运算中被使用,日期被转换为一个数字,当你将日期转换为数字时,你得到的数字是从 - (例如, getTime()
)。
长版本:
-
对于像
Date
s,它调用抽象操作ToPrimitive
,首选类型为数字。 -
对于大多数类型的对象(包括
Date
s),ToPrimitive
调用抽象操作< a href =http://www.ecma-international.org/ecma-262/5.1/#sec-8.12.8 =nofollow>[[DefaultValue]]
,将首选类型作为提示传递。 -
[[DefaultValue]]
with hint =numbercall
valueOf
对象。 (valueOf
是一个真正的方法,与上面的抽象操作不同。) -
对于
日期
对象,valueOf
返回时间值,您从getTime
获得的值。
旁注:没有理由使用 var timeStamp = 1 * new Date()
而不是说, var timeStamp = + new Date()
,具有相同的效果。或者当然,在任何现代引擎(和垫片是微不足道的), var timeStamp = Date.now()
( more on Date.now
)。 p>
I came across this piece of code var timeStamp = 1 * new Date();
and to my surprise it returned value in milliseconds since 1970/01/01. This is equivalent to using .getTime()
method!
What's happening under the hood? Does Type Conversion concept work here, which basically converts new Date()
value into the milliseconds?
What's happening under the hood?
The short version:
Because it's being used in a math operation, the date is converted to a number, and when you convert dates to numbers, the number you get is the milliseconds-since-the-Epoch (e.g., getTime()
).
The long version:
The multiplication operator calls the abstract operation
ToNumber
on its operands.For objects like
Date
s, that calls the abstract operationToPrimitive
on the object, with the "preferred type" being "number".For most types of objects (including
Date
s),ToPrimitive
calls the abstract operation[[DefaultValue]]
, passing along the preferred type as the "hint".[[DefaultValue]]
with hint = "number" callsvalueOf
on the object. (valueOf
is a real method, unlike the abstract operations above.)For
Date
objects,valueOf
returns the "time value," the value you get fromgetTime
.
Side note: There's no reason I can think of to use var timeStamp = 1 * new Date()
rather than, say, var timeStamp = +new Date()
, which has the same effect. Or of course, on any modern engine (and the shim is trivial), var timeStamp = Date.now()
(more on Date.now
).
这篇关于与日期对象的乘法 - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!