使用Babel扩展Date类

时间:2016-06-03 08:02:21

标签: javascript date inheritance ecmascript-6

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

"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.

那么,如何在不破坏代码的情况下对这些代码进行简化呢?

1 个答案:

答案 0 :(得分:4)

由于ES5的限制,Babel无法开箱即用subclass a lot of built-ins

  

应根据具体情况评估内置子类可分性   因为诸如HTMLElement 之类的类可以被分类,而许多诸如   DateArrayError 无法归因于ES5引擎限制。

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