2017-07-03 42 views
1

我想寫ReasonML編譯爲這個JS:如何在Reason(ReasonML)中使用[@ bs.this] BuckleScript屬性?

function main(example) { 
    example.foo = function() { 
     console.log(this) 
    } 
} 

這裏是我的原因:

let module Example = { 
    type t; 
    external set_foo_method : t => (t => unit [@bs.this]) => unit = "foo" [@@bs.set]; 
}; 

let main = fun example => Example.set_foo_method example (fun [@bs.this] x => { 
    Js.log(x); 
}); 

我得到的行和列的語法錯誤第二[@bs.this]

File "/Users/maxwellheiber/dev/rerect/src/demo.re", line 6, characters 62-64: 
Error: 742: <SYNTAX ERROR> 

我正在關注@bs.this的BuckleScript文檔。

與OCaml相比,使用BuckleScript綁定到this的原因與原因不同嗎?下面OCaml的(而不是理性)與BuckleScript屬性沒有錯誤編譯到正確的JS:

module Example = struct 
    type t 
    external set_foo_method : t -> (t -> unit [@bs.this]) -> unit = "foo" [@@bs.set] 
end 

let main example = Example.set_foo_method example (fun [@bs.this] x -> Js.log(x)) 

如何使用[@bs.this] BuckleScript屬性的原因,產生使用this JS?

回答

3

是的,屬性優先,這是不幸的微妙不同。 Reason Tools(這是偉大的轉換小片段是這樣)說,這是你想要什麼:

module Example = { 
    type t; 
    external set_foo_method : t => (t => unit) [@bs.this] => unit = "foo" [@@bs.set]; 
}; 

let main example => Example.set_foo_method example ((fun x => Js.log x) [@bs.this]); 

它將編譯爲

function main(example) { 
    example.foo = (function() { 
     var x = this ; 
     console.log(x); 
     return /*() */0; 
    }); 
    return /*() */0; 
} 
+0

感謝您對理性的工具鏈接 –