gpt4 book ai didi

javascript - 使用 Babel 扩展 Date 类

转载 作者:行者123 更新时间:2023-11-28 15:08:48 25 4
gpt4 key购买 nike

我想使用 extendsDate 类扩展一个类。

"use strict";

class XDate extends Date {
format () {
return "foo";
}
}

let d = new XDate();
console.log(d.format());
console.log(d.getFullYear());

本地运行 ES2015 的东西时它确实工作得很好。但是当把它转译成 ES5 时,它就不再工作了:

"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var XDate = function (_Date) {
_inherits(XDate, _Date);

function XDate() {
_classCallCheck(this, XDate);

return _possibleConstructorReturn(this, Object.getPrototypeOf(XDate).apply(this, arguments));
}

_createClass(XDate, [{
key: "format",
value: function format() {
return "foo";
}
}]);

return XDate;
}(Date);

var d = new XDate();
console.log(d.format());
console.log(d.getFullYear());

它以这个错误结束:

console.log(d.getFullYear());
^

TypeError: this is not a Date object.

那么,如何在不破坏代码的情况下对其进行 babelify 呢?

最佳答案

Babel 不能 subclass a lot of built-ins由于 ES5 的限制,开箱即用。

Built-in subclassability should be evaluated on a case-by-case basis as classes such as HTMLElement can be subclassed while many such as Date, Array and Error cannot be due to ES5 engine limitations.

您可以尝试transform-builtin-extend插入。它没有明确将Date列为支持的用例之一。

关于javascript - 使用 Babel 扩展 Date 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37609080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com