2

对于下面的 JavaScript 代码,我该如何用 ReasonML 编写它?

class HelloWorld extends HTMLElement {
  constructor() {
    super();
    // Attach a shadow root to the element.
    let shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = `<p>hello world</p>`;
  }
}

我找不到任何关于在 ReasonML 中编写类的文档?我不能使用普通对象/类型,因为我需要从不适用于ES 样式类的 HTMLElement 类进行扩展。

我已经研究了这个现有的问题 - How to extend JS class in ReasonML然而,这是另一回事。要编写 Web 组件,我们需要扩展HTMLElement并且必须使用new关键字调用它。ES5 样式扩展机制不起作用。

4

1 回答 1

4

你不能。至少不是直接的,因为 BuckleScript(Reason 用来编译成 JavaScript)以 ES5 为目标,因此不了解 ES6 类。

幸运的是,ES6 类不需要特殊的运行时支持,而是作为语法糖实现的,这就是为什么您可以将 ES6 转换为 ES5,如链接到的问题所示。然后,您真正需要做的就是将此转换后的输出转换为 ReasonML:

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 BaseElement = (function (_super) {
    __extends(BaseElement, _super);
    function BaseElement() {
        _super.call(this);
    }
    return BaseElement;
}(HTMLElement));

根据您实际需要的特定类功能,您可以稍微简化一下。

于 2019-01-08T18:17:40.887 回答