2016-06-03 4 views
0

을 사용하여 Date 클래스의 클래스를 확장하고 싶습니다.Babel을 사용하여 Date 클래스 확장하기

"use strict"; 

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

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

기본적으로이 ES2015 항목을 실행하면 정상적으로 작동합니다. ES5로를 transpiling 때, 그것은 더 이상 작동하지 않습니다 :

"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 수 있습니까?

답변

3

바벨은 ES5 제한으로 인해 subclass a lot of built-ins을 즉시 구입할 수 없습니다.

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

transform-builtin-extend 플러그인을 사용해보십시오. 지원되는 사용 사례 중 하나로 명시 적으로 Date을 나열하지 않습니다.