请注意:此问题与 Google 的 Closure Compiler 的使用有关。它与 ES6 没有直接关系,因为那部分是有效的。
我用 ES6 编写了一个类,它扩展了 native Date 对象。这是一个大类,但这是一个简化版本:
class Dative extends Date {
constructor (dateData) {
super();
super.setTime(Date.parse(dateData));
}
addMilliseconds (ms) {
super.setTime(super.getTime() + ms);
}
}
上面的代码在 Chrome 和 Firefox 中运行良好。但是,当我通过 Closure Compiler 传递它时,它会抛出错误:
Uncaught TypeError: Method Date.prototype.setTime called on incompatible receiver [object Object]
更新:在编译版本中调用 native Date 方法也会失败,但在未编译的情况下工作正常,并显示一条消息说这不是 Date 对象。
我不明白的是,为什么以原始形式运行的代码在编译时会中断。
是我做错了什么,还是编译器错误?
我使用的是最新版本的 compiler.jar。作为引用,这是闭包编译器生成的内容:
var $jscomp = {
scope: {},
inherits: function(a, b) {
function d() {}
d.prototype = b.prototype;
a.prototype = new d;
a.prototype.constructor = a;
for (var c in b)
if (Object.defineProperties) {
var e = Object.getOwnPropertyDescriptor(b, c);
e && Object.defineProperty(a, c, e)
} else
a[c] = b[c]
}
}
, Dative = function(a) {
Date.call(this);
Date.prototype.setTime.call(this, Date.parse(a))
};
$jscomp.inherits(Dative, Date);
Dative.UTC = Date.UTC;
Dative.parse = Date.parse;
Dative.now = Date.now;
Dative.prototype.addMilliseconds = function(a) {
Date.prototype.setTime.call(this, Date.prototype.getTime.call(this) + a)
};
//# sourceMappingURL=./DativeShort.map
最佳答案
Date
在 ES5 中不可继承。所以你想要的东西首先在 ES5 环境中是不可能的。
转译后的代码也无法在 ES6 环境中运行。来自specification
The Date constructor is designed to be subclassable. It may be used as the value of an extends clause of a class definition. Subclass constructors that intend to inherit the specified Date behaviour must include a super call to the Date constructor to create and initialize the subclass instance with a [[DateValue]] internal slot.
如果不调用 super
,它将无法工作。 Date.call(this);
不能解决问题。基本上,如果您将代码转换为 ES5,则子类化内置类型是行不通的。
所以不,这不是 Google Closure 的问题。
关于javascript - 为什么 Google Closure Compiler 在扩展 Date() 的 ES6 对象上失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38954597/