[英]TypeScript | Extends error (Uncaught TypeError: this is not a X object)
I create this class: 我创建这个类:
class trueDate extends Date {
constructor(date: string) {
super(date)
}
getDay(): number {
var day = super.getDay()
return day === 0 ? 7 : day
}
addDate(date: number) {
super.setTime(super.getTime() + date * 86400)
}
}
But, when I call methods on an inherited class (for example: trueDateObj.getDate() ) get the error: 但是,当我在继承类上调用方法时(例如: trueDateObj.getDate() )得到错误:
Uncaught TypeError: this is not a Date object.
未捕获的TypeError:这不是Date对象。
Output JS code: 输出JS代码:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var trueDate = (function (_super) {
__extends(trueDate, _super);
function trueDate(date) {
_super.call(this, date);
}
trueDate.prototype.getDay = function () {
var day = _super.prototype.getDay.call(this);
return day === 0 ? 7 : day;
};
trueDate.prototype.addDate = function (date) {
_super.prototype.setTime.call(this, _super.prototype.getTime.call(this) + date * 86400);
};
return trueDate;
})(Date);
I create new object like this: 我创建这样的新对象:
var trueDateObj = new trueDate("date-string")
Firefox error: Firefox错误:
TypeError: getDate method called on incompatible Object
TypeError:在不兼容的Object上调用getDate方法
You should not (and can not in most if not all cases) inherit from native/primitive types. 您不应该(并且在大多数情况下不能在所有情况下都不能)继承本机/基元类型。 Extending primitive types is considered bad practice even in pure javascript (read the section 'Bad practice: Extension of native prototypes' here to learn a bit about why).
扩展原始类型被认为是不好的做法,即使在纯JavaScript(阅读部分“坏的做法:原生原型的扩展” 在这里学习了一下为什么)。
In this case it will not work because the Date class does not conform to how the inheritance works in typescript. 在这种情况下,它将无法工作,因为Date类不符合继承在typescript中的工作方式。
If you want to do something like this what you should do is a wrapper class or use something already existing, like moment.js for example. 如果你想做这样的事情你应该做的是一个包装类或使用已经存在的东西,例如moment.js。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.