Temporal.Instant.prototype.valueOf()
valueOf()
方法 Temporal.Instant
实例会抛出一个 TypeError
,这会阻止 Temporal.Instant
实例在算术或比较运算中被 隐式转换为原始值。
语法
js
valueOf()
参数
无。
返回值
无。
异常
TypeError
-
总是抛出。
描述
由于 原始值转换 和 数字转换 都会在调用 toString()
之前调用 valueOf()
,如果 valueOf()
不存在,那么像 instant1 > instant2
这样的表达式会隐式地将它们作为字符串进行比较,这可能会产生意外的结果。通过抛出 TypeError
,Temporal.Instant
实例可以防止此类隐式转换。你需要使用 Temporal.Instant.prototype.epochNanoseconds
显式地将它们转换为数字,或者使用 Temporal.Instant.compare()
静态方法来比较它们。
示例
Temporal.Instant 上的算术和比较运算
所有在 Temporal.Instant
实例上的算术和比较运算都应使用专用方法,或显式将其转换为原始值。
js
const instant1 = Temporal.Instant.fromEpochMilliseconds(0);
const instant2 = Temporal.Instant.fromEpochMilliseconds(1000);
instant1 > instant2; // TypeError: can't convert Instant to primitive type
instant1.epochNanoseconds > instant2.epochNanoseconds; // false
Temporal.Instant.compare(instant1, instant2); // -1
instant2 - instant1; // TypeError: can't convert Instant to primitive type
instant2.since(instant1).toString(); // "PT1S"
规范
规范 |
---|
Temporal # sec-temporal.instant.prototype.valueof |
浏览器兼容性
加载中…