Temporal.PlainYearMonth.prototype.valueOf()
valueOf() 方法,針對 Temporal.PlainYearMonth 例項,會丟擲一個 TypeError。這可以防止 Temporal.PlainYearMonth 例項在算術或比較操作中被 隱式轉換為原始型別。
語法
js
valueOf()
引數
無。
返回值
無。
異常
TypeError-
總是丟擲。
描述
由於 原始型別轉換 和 數字轉換 都會在呼叫 toString() 之前呼叫 valueOf(),如果 valueOf() 不存在,那麼像 yearMonth1 > yearMonth2 這樣的表示式會隱式地將它們作為字串進行比較,這可能會產生意外的結果。透過丟擲 TypeError,Temporal.PlainYearMonth 例項可以防止這種隱式轉換。你需要使用 Temporal.PlainYearMonth.prototype.toString() 顯式地將它們轉換為字串,或者使用 Temporal.PlainYearMonth.compare() 靜態方法來比較它們。
示例
Temporal.PlainYearMonth 上的算術和比較操作
Temporal.PlainYearMonth 例項上的所有算術和比較操作都應該使用專門的方法,或者顯式地將它們轉換為原始型別。
js
const ym1 = Temporal.PlainYearMonth.from("2021-01");
const ym2 = Temporal.PlainYearMonth.from("2021-07");
ym1 > ym2; // TypeError: can't convert PlainYearMonth to primitive type
Temporal.PlainYearMonth.compare(ym1, ym2); // -1
ym2 - ym1; // TypeError: can't convert PlainYearMonth to primitive type
ym2.since(ym1).toString(); // "P6M"
規範
| 規範 |
|---|
| Temporal # sec-temporal.plainyearmonth.prototype.valueof |
瀏覽器相容性
載入中…