Temporal.PlainMonthDay.prototype.valueOf()

可用性有限

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

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

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

語法

js
valueOf()

引數

無。

返回值

無。

異常

TypeError

總是丟擲。

描述

由於原始型別轉換數字轉換都會在 toString() 之前呼叫 valueOf(),因此,如果 valueOf() 不存在,那麼像 monthDay1 > monthDay2 這樣的表示式會隱式地將它們作為字串進行比較,這可能會導致意外的結果。透過丟擲 TypeErrorTemporal.PlainMonthDay 例項可以防止這種隱式轉換。你需要使用 Temporal.PlainMonthDay.prototype.toString() 顯式地將它們轉換為字串。

示例

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

所有在 Temporal.PlainMonthDay 例項上的算術和比較操作都應該使用專用方法,或者顯式地將它們轉換為原始型別。

js
const md1 = Temporal.PlainMonthDay.from("01-01");
const md2 = Temporal.PlainMonthDay.from("07-01");
md1 > md2; // TypeError: can't convert PlainMonthDay to primitive type
Temporal.PlainDate.compare(
  md1.toPlainDate({ year: 2021 }),
  md2.toPlainDate({ year: 2021 }),
); // -1

md2 - md1; // TypeError: can't convert PlainMonthDay to primitive type
md2
  .toPlainDate({ year: 2021 })
  .since(md1.toPlainDate({ year: 2021 }))
  .toString(); // "P181D"

規範

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

瀏覽器相容性

另見