如何在ReasonML中扩展JS类 [英] How to extend JS class in ReasonML

查看:140
本文介绍了如何在ReasonML中扩展JS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个 es6 类的类:

For example, I have an es6-like class:

class Foo {...}

我想扩展它:

class Bar扩展了Foo {...}

reason-react 文档中,我找到了示例,但我是不确定它是否适合我:

In reason-react documentation I found examples, but I'm not sure that it's appropriate for me:

let component = ReasonReact.reducerComponent "TodoAppRe";
let make _children => {
  ...component,
  initialState: fun () => {count: 0},
  <...>

但是当我尝试以这种方式编写代码时,我收到一个错误:

But when i try to write code in this style, i get an error:

let myclass unit => {
  ...mysuperclass,
    hello: fun () => {
      Js.log "FooBar";
    }
};




错误:未绑定记录字段更新

Error: Unbound record field update

(在本例中, mysuperclass 来自第三方js-library)。

(In this example mysuperclass is external from 3rd-party js-library).

也许我做错了什么?

推荐答案

让foo吧=> {... baz,quux:...} 不是继承的语法,它是组合的语法。具体来说,它采用 baz 记录值(不是对象)并更新其 quux 成员(不是方法)。

let foo bar => { ...baz, quux: ... } is not a syntax for inheritance, it's a syntax for composition. Specifically, it's taking the baz record value (not object) and updating its quux member (not method).

如果你想在Reason / BuckleScript中扩展JS类,首先要记住BuckleScript生成的代码与ES5向后兼容,因此你不需要使用巴贝尔。事实上,BuckleScript不直接支持扩展类。

If you want to extend a JS class in Reason/BuckleScript, first keep in mind that BuckleScript generates code that's backwards-compatible with ES5, so that you don't need to use Babel. In fact BuckleScript doesn't directly support extending a class.

但是,你可以使用BuckleScript的<$在原始源代码中包含原始JavaScript c $ c> [%% bs.raw] 属性( https://bucklescript.github.io/bucklescript/Manual.html#_embedding_raw_js_code_as_statements ):

But, you can include raw JavaScript in your Reason source code using BuckleScript's [%%bs.raw] attribute ( https://bucklescript.github.io/bucklescript/Manual.html#_embedding_raw_js_code_as_statements ):

/* MyProject_Animal.re */

[%%bs.raw {|

// Dummy class for example:
class Animal {
  speak() {}
}

// or:
// import Animal from "somewhere";

class Dog extends Animal {
  _name;

  constructor(name) {
    super();
    this._name = name;
  }

  speak() {
    console.log(`${this._name} says woof!!`);
    super.speak();
  }
}
|}];

然后你可以写一个绑定到 Dog 下面代码中的类:

And then you can write a binding to the Dog class in the code below that:

module Animal_Dog = {
  type t;

  [@bs.new] external make: string => t = "Dog";
  /* Need this to ensure correct usage in other modules */
  let make = make;

  [@bs.send] external speak: t => unit = "";
};

let spot = Animal_Dog.make("Spot");
Animal_Dog.speak(spot);

但是,请记住,自从这个ES2015以来,如果你想要它,你将需要通过Babel运行它与ES2015之前的浏览器向后兼容。

But, remember that since this ES2015, you will need to run it through Babel if you want it to be backwards-compatible with pre-ES2015 browsers.

这篇关于如何在ReasonML中扩展JS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆