我不明白 的行为Intl.DateTimeFormat
。
它不会暴露我对 JavaScript 对象所期望的行为。我想明白为什么?
下面的代码片段演示了format
onDateTimeFormat
方法不能被覆盖。这怎么可能?
const itDateTimeFormat1 = new window.Intl.DateTimeFormat('it-CH');
const originalFormat = itDateTimeFormat1.format;
itDateTimeFormat1.format = function(date){ return 'Overriden! ' + originalFormat(date)};
console.log(itDateTimeFormat1.format(new Date())); // -> 13/7/2017
同样从原型继承派生DateTimeFormat
似乎是不可能的。以下代码段引发错误:
const itDateTimeFormat2 = new window.Intl.DateTimeFormat('it-CH');
const wrappedDateTimeFormat = Object.create(itDateTimeFormat2);
wrappedDateTimeFormat.format = function(date){ return 'Overriden! ' };
console.log(wrappedDateTimeFormat.format(new Date()));
// Firefox:
// TypeError: Intl.DateTimeFormat.prototype.format called on value that's not an object initialized as a DateTimeFormat
// Chrome:
// Uncaught TypeError: Method format called on incompatible receiver #<DateTimeFormat>
为什么DateTimeFormat
不像一个“正常”的 JavaScript 对象?
如何DateTimeFormat
防止覆盖方法?
如何DateTimeFormat
防止覆盖派生对象?