不同的ReasonML外部声明有什么含义? [英] What are the Implications of Different ReasonML External Declarations?
问题描述
在下面的示例中,两个外部声明都使用稍有不同的ReasonML函数结构来实现 same 功能。
In the examples below, both external declarations achieve the same functionality with slightly different ReasonML function structures.
外部声明 style 是否会影响ReasonML函数结构以外的任何内容(例如性能)?另外,ReasonML是否具有建议的外部声明样式?
Does external declaration style impact anything (e.g. performance) beyond ReasonML function structure? Also, does ReasonML have a "suggested" external declaration "style"?
类型声明
type dom;
type element;
外部声明样式1
[@bs.val]
external dom: dom = "document";
[@bs.send.pipe : dom]
external get_by_id: string => element = "getElementById";
外部声明样式2
[@bs.scope "document"] [@bs.val]
external by_id: string => element = "getElementById";
ReasonML函数调用
let tag1 = dom |> get_by_id("main");
let tag2 = by_id("main")
推荐答案
主要区别在于使用方式。
The main difference should be apparent from how they're used.
let tag1 = dom |> get_by_id("main"); // has two parts
let tag2 = by_id("main") // has only one part
具有两个部分意味着您可以将每个部分与其他部分交换出来,只要它们具有相同的类型签名即可。例如,我们可以将 dom
(值)替换为 dom
(类型)的另一个实例:
Having two parts means you can swap each part out with other parts, as long as they have the same type signature. We could for example replace dom
(the value) with a different instance of dom
(the type):
[@bs.new]
external make_doc: unit => dom = "Document";
let tag3 = make_doc() |> get_by_id("main");
但是,这还有一个更微妙的含义。有两个部分意味着您可以在不同的上下文中评估这些部分。这不是那么容易说明,但是考虑一下这个人为的例子:
There's also a more subtle implication to this, however. Having two parts means you can evaluate the parts in different contexts. This isn't as easy to illustrate, but consider this contrived example:
[@bs.val]
external dom: dom = "document";
let dom1 = dom;
[%%raw {|var document = null|}];
let dom2 = dom;
let tag1 = dom1 |> get_by_id("main");
let tag2 = dom2 |> get_by_id("main");
let tag3 = by_id("main")
dom1
和 dom2
在这里是指不同的值。使用 dom1
将按预期工作,而使用 dom2
将崩溃。和 by_id
一样。
dom1
and dom2
here refer to different values. Using dom1
will work as expected, while using dom2
will crash. As will by_id
.
那么您应该使用哪个?好吧,这取决于您的需求。如果您将始终使用当前作用域中的文档
,请使用 bs.scope
,因为这样做更加方便。如果不这样做,或者要使用具有多个不同值的相同函数,请使用 @ bs.send
/ @ bs.send.pipe
。
So which should you use? Well, that depends on what you need. If you will always use the document
currently in scope, use bs.scope
since that's more convenient. If you don't, or you want to use the same function with several different values, use @bs.send
/@bs.send.pipe
.
这篇关于不同的ReasonML外部声明有什么含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!