我想创建一个新的Date
后代类并覆盖构造函数:
export class MyDate extends Date {
constructor(str: string) {
super(str);
}
}
现在,如果我创建一个MyDate
对象,它就不起作用了:
var myDate = new MyDate("2016-10-20T12:30:00+0200");
console.log(myDate.toDateString()); // it crashes, myDate is incorrect
我得到TypeError: Method Date.prototype.toDateString called on incompatible receiver [object Object]
。
如何覆盖Date
构造函数?有可能吗?
答案 0 :(得分:2)
根据this question and the accepted answer,这是因为ES5中不允许继承Date
。以下ES6代码适用于Chrome,因为Chrome本身支持ES6类(除了我删除了类型注释外,它与您的代码完全相同):
class MyDate extends Date {
constructor(str) {
super(str);
}
}
var myDate = new MyDate("2016-10-20T12:30:00+0200");
console.log(myDate.toDateString());

如果您只需要在本机支持ES6类的环境中工作,请将TypeScript的--target
编译器选项更改为'es6'
。否则,您将需要做其他事情。
一种解决方法可能是定义MyDate
,使其具有Date
作为成员变量。例如:
class MyDate {
private date: Date;
constructor(str: string) {
this.date = new Date(str);
}
toDateString(): string {
return this.date.toDateString();
}
}