gpt4 book ai didi

javascript - coffeescript 总是返回

转载 作者:行者123 更新时间:2023-11-29 17:15:43 25 4
gpt4 key购买 nike

关于 Coffee Script,我有一个可能很愚蠢的问题要问。我给了它第二次机会,但为什么它返回一切

它与函数的最后一条语句/行有什么关系吗?以及如何禁用它?将评论或其他内容作为最终的“表达”,我知道这是一个“记录在案”的功能,但不是;不,这不是真的,我如何到处返回?并节省下载/执行时间?

肯定是这种行为把 jit 搞砸了?

(locate =
getPosition: () ->
# Check we support geolocation
throw Exception 'Your browser doesn\'t support location based services!' if !navigator.geolocation

navigator.geolocation.getCurrentPosition (pos) ->
console.log pos
)

编译为

(function() {
var locate;

locate = {
getPosition: function() {
if (!navigator.geolocation) {
throw Exception('Your browser doesn\'t support location based services!');
}
return navigator.geolocation.getCurrentPosition(function(pos) {
return console.log(pos);
});
}
};

}).call(this);

[编辑]

我关心的原因是这只是我构建的应用程序的一个非常大的库中的一个,如果我们说有 500 个函数并且其中 200 个对 dom 执行某些操作而不是返回数字或对象之类的东西,额外的 200 次返回是我不想要或不需要的额外 1.2k 数据。

此外,一个没有返回值的函数返回undefined,一个返回null的函数很好,不需要解释。如果我愚蠢到去检查这个,那它就全错了。

我确定会有一些性能差异,但我不知道,现在我没有时间做一些 jsperfs,但我很感兴趣。

Undefined and null

最佳答案

是的,coffeescript 将始终返回函数的最后一行。它可以做到这一点,因为 coffeescript 中的一切都是表达式。

来自docs :

Everything is an Expression (at least, as much as possible)

You might have noticed how even though we don't add return statements to CoffeeScript functions, they nonetheless return their final value. The CoffeeScript compiler tries to make sure that all statements in the language can be used as expressions. Watch how the return gets pushed down into each possible branch of execution in the function below.

他们的例子可以看here

您仍然可以使用return 语句进行短路返回

Even though functions will always return their final value, it's both possible and encouraged to return early from a function body writing out the explicit return (return value), when you know that you're done.

关于javascript - coffeescript 总是返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18315606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com