顶级变量不是全局范围的,并且返回值在 CoffeeScript 中是强制的
funName = () ->
$(".foo").addClass("bar");
编译到匿名函数的作用域中。从控制台调用 funName
会导致 undefined
。
(function() {
var funName;
funName = function() {
return $(".foo").addClass("bar");
};
}).call(this);
像这样编译的原因是什么?我该如何使用它?
此外,任何有关使用 CoffeeScript 的函数中的强制返回的见解都会很棒。为什么会这样呢?我如何需要因此而采用不同的编码?
funName = () ->
$(".foo").addClass("bar");
Compiles into the scope of an anonymous function. Calling funName
from the console results in undefined
.
(function() {
var funName;
funName = function() {
return $(".foo").addClass("bar");
};
}).call(this);
What's its reasoning for compiling like this and how do I work with it?
Also any insight on the mandatory return within functions using CoffeeScript would be great. Why is it like that? How do I need to code differently because of it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
迈克在这里回答了主要问题。模块化包装器是 CoffeeScript 新手的常见困惑点,如以下相关问题所示:
至于您的另一个问题:如果您不希望函数返回任何内容,只需将该函数的最后一行设置为
return
本身,或者等效地未定义
。两者都会编译为没有返回
的函数。例如:编译时请
注意,正在进行讨论(issue 899)关于定义无返回函数的可能替代语法。如果当前的提案被接受,您就可以将您的函数编写为
如果您喜欢该语法,则应该表达您对它的支持。
Mike has answered the main question here. The modular wrapper a common point of confusion for CoffeeScript newcomers, as illustrated by these related questions:
As to your other question: If you don't want a function to return anything, simply make the last line of that function either
return
by itself or, equivalently,undefined
. Either will compile to a function with noreturn
. For instance:compiles to
Note that there is an ongoing discussion (issue 899) about a possible alternative syntax for defining no-return functions. If the current proposal were accepted, you'd be able to write your function as
If you like that syntax, you should voice your support for it.
如果您想创建一个全局
funName
,请尝试使用root = Exports ? this
然后root.funName = ...
如How do我在 CoffeeScript 中定义全局变量?If you want to create a global
funName
try usingroot = exports ? this
and thenroot.funName = ...
as described at How do I define global variables in CoffeeScript?我知道这可能是一个较旧的线程,但我遇到了同样的问题,并注意到一个有趣的命令,您可以添加到编译器环境中来解决这个问题。
命令-b或--bare用于编译JavaScript而不顶级函数安全包装器。在编译 CoffeeScript 文件时添加该命令后,它删除了那个奇怪的包装器:
我使用 WebStorm 作为我的 IDE 环境,这是我使用的编译器语句:
I know this may be an older thread, but I've encountered the same problem and noticed an interesting command you can add into the compiler enviroment to fix this problem.
The command -b or --bare is used to compile the JavaScript without the top-level function safety wrapper. After I added that command when I compiled my CoffeeScript file, it removed that odd wrapper:
I use WebStorm as my IDE enviroment and this is my compiler statement I use: