Temporal.PlainTime.prototype.valueOf()

可用性有限

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

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

Temporal.PlainTime 例項的 valueOf() 方法會丟擲 TypeError,這可以阻止 Temporal.PlainTime 例項在算術或比較操作中被 隱式轉換為原始值

語法

js
valueOf()

引數

無。

返回值

無。

異常

TypeError

總是丟擲。

描述

由於 原始值轉換數字轉換 都會在呼叫 toString() 之前呼叫 valueOf(),因此如果 valueOf() 不存在,則像 time1 > time2 這樣的表示式會隱式地將它們作為字串進行比較,這可能會產生意外的結果。透過丟擲 TypeErrorTemporal.PlainTime 例項可以阻止此類隱式轉換。您需要使用 Temporal.PlainTime.prototype.toString() 顯式地將它們轉換為字串,或者使用 Temporal.PlainTime.compare() 靜態方法來比較它們。

示例

Temporal.PlainTime 上的算術和比較操作

Temporal.PlainTime 例項的所有算術和比較操作都應使用專用方法或顯式將它們轉換為原始值。

js
const time1 = Temporal.PlainTime.from("00:00:00");
const time2 = Temporal.PlainTime.from("12:00:00");
time1 > time2; // TypeError: can't convert PlainTime to primitive type
Temporal.PlainTime.compare(time1, time2); // -1

time2 - time1; // TypeError: can't convert PlainTime to primitive type
time2.since(time1).toString(); // "PT12H"

規範

規範
Temporal
# sec-temporal.plaintime.prototype.valueof

瀏覽器相容性

另見