Temporal.Instant.prototype.valueOf()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

valueOf() 方法 Temporal.Instant 例項會丟擲一個 TypeError,這會阻止 Temporal.Instant 例項在算術或比較運算中被 隱式轉換為原始值

語法

js
valueOf()

引數

無。

返回值

無。

異常

TypeError

總是丟擲。

描述

由於 原始值轉換數字轉換 都會在呼叫 toString() 之前呼叫 valueOf(),如果 valueOf() 不存在,那麼像 instant1 > instant2 這樣的表示式會隱式地將它們作為字串進行比較,這可能會產生意外的結果。透過丟擲 TypeErrorTemporal.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

瀏覽器相容性

另見