简体   繁体   English

如何构造一个js对象并用js_of_ocaml调用它的方法?

[英]How to construct a js object and call its methods with js_of_ocaml?

I try to build an application using js_of_ocaml. 我尝试使用js_of_ocaml构建应用程序。 Let's say I have the following code in javascript : 假设我在javascript中有以下代码:

function MyFunction(){ this.name = "a" }
MyFunction.prototype.setName = function(arg){ this.name = arg }

How to write in OCaml/js_of_caml a code that will have the same effect as the js code below ? 如何在OCaml / js_of_caml中编写一个与下面的js代码具有相同效果的代码?

val myInstance = new MyFunction();
myInstance.setName("Joe");

I tried to write something like : 我试着写下这样的东西:

let onload _ =
  let myInstance = Js.Unsafe.new_obj (Js.Unsafe.variable "MyFunction") [||] in
  Js.Unsafe.call (Js.Unsafe.variable "MyFunction.prototype.setName") myIntance [|Js.Unsafe.inject "Joe"|];
  Js._false ;;
let _ = Html.window##onload <- Html.handler onload;

The constructor is called but I have errors following so it doesn't seem to be the right way to do it. 调用构造函数,但我有错误,因此它似乎不是正确的方法。 I have also tried the Js.Unsafe.meth_call function but it's not better. 我也尝试过Js.Unsafe.meth_call函数,但它并不是更好。

Any help would be appreciated. 任何帮助,将不胜感激。

Your Unsafe version should work with 您的不安全版本应该可以使用

let onload _ =
  let myInstance = Js.Unsafe.new_obj (Js.Unsafe.variable "MyFunction") [||] in
  Js.Unsafe.meth_call myInstance "setName" [|Js.Unsafe.inject (Js.string "Joe")|];
  Js._false ;;
 let _ = Dom_html.window##onload <- Dom_html.handler onload;

it generate 它生成

function _A_(_a_){new MyFunction().setName("Joe");return _M_}

A safer (typed) version would be 一个更安全(打字)的版本

class type myFun = object
  method setName : Js.js_string Js.t -> unit Js.meth
end
let myFun : myFun Js.t Js.constr =
  Js.Unsafe.global##_MyFunction (* same as Js.Unsafe.variable "MyFunction" *)

let onload _ =
  let myInstance = jsnew myFun () in
  myInstance##setName(Js.string "Joe");
  Js._false ;;
let _ = Dom_html.window##onload <- Dom_html.handler onload;

it generate the following JavaScript 它生成以下JavaScript

var _Q_=_d_.MyFunction;
function _A_(_a_){new _Q_().setName("Joe");return _M_}
_d_.onload=  .... _A_(..)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM