【问题标题】:OOP - How to call a class method internally in ReasonOOP - 如何在 Reason 内部调用类方法
【发布时间】:2017-10-20 08:14:42
【问题描述】:

我有一个testFactory 课程。目的是能够传入工厂,然后控制台输出结果以用于演示目的。到目前为止,当尝试在测试方法中调用 createProductA 时,编译器会抱怨 createProductA 未绑定 (Unbound value createProductA)。

在类内部调用方法的正确语法是什么?

class testFactory (factory: abstractFactory) => {
  as _;
  pub createProductA => factory#createProductA;
  pub createProductB => factory#createProductB;

  pub test () => {
    Js.log createProductA;
    Js.log createProductB;
  }
};

【问题讨论】:

  • 我不知道我之前是否提到过,但你可能想看看Real World OCaml's section on classes。您可以使用reason-tools 将 OCaml 代码转换为 Reason。
  • 我确实读过那一章,而且我不断地重读它(尤其是在地铁上)并尝试使用 _ 和 #。可能是在赶时间的时候,我忽略了一些东西。一如既往的感谢。

标签: oop methods ocaml reason


【解决方案1】:

这就是类定义的as _; 部分的用武之地,如果您想知道它是干什么用的。

createProductAcreateProductB 是方法,而不是函数,因此需要在对象上调用它们。 Reason/OCaml 不会自动将当前对象绑定到像 thisself 这样的名称,而是让你去做,这正是 as 所做的,而 _ 意味着,像往常一样, “我不在乎这个”。因此,如果您将 as _; 更改为例如as self; 您可以在别处引用 self 作为当前对象。

试试这个:

class testFactory (factory: abstractFactory) => {
  as self;
  pub createProductA => factory#createProductA;
  pub createProductB => factory#createProductB;

  pub test () => {
    Js.log self#createProductA;
    Js.log self#createProductB;
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    相关资源
    最近更新 更多