![](/img/trans.png)
[英]Uncaught TypeError: Class extends value #<Object> is not a constructor or null
[英]TypeScript | Extends error (Uncaught TypeError: this is not a X object)
我創建這個類:
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)
}
}
但是,當我在繼承類上調用方法時(例如: trueDateObj.getDate() )得到錯誤:
未捕獲的TypeError:這不是Date對象。
輸出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);
我創建這樣的新對象:
var trueDateObj = new trueDate("date-string")
Firefox錯誤:
TypeError:在不兼容的Object上調用getDate方法
您不應該(並且在大多數情況下不能在所有情況下都不能)繼承本機/基元類型。 擴展原始類型被認為是不好的做法,即使在純JavaScript(閱讀部分“壞的做法:原生原型的擴展” 在這里學習了一下為什么)。
在這種情況下,它將無法工作,因為Date類不符合繼承在typescript中的工作方式。
如果你想做這樣的事情你應該做的是一個包裝類或使用已經存在的東西,例如moment.js。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.