Top-level variables aren#39;t globally-scoped and return values are mandatory in CoffeeScript(顶级变量不是全局范围的,在 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?
Mike has answered the main question here. The modular wrapper a common point of confusion for CoffeeScript newcomers, as illustrated by these related questions:
- How do I define global variables in CoffeeScript?
- Why use the javascript function wrapper (added in coffeescript) ".call(this)"
- Getting rid of CoffeeScript's closure wrapper
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 no return
. For instance:
funName = ->
$(".foo").addClass "bar"
return
compiles to
var funName;
funName = function() {
$(".foo").addClass("bar");
};
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
funName = -/> $(".foo").addClass "bar"
If you like that syntax, you should voice your support for it.
这篇关于顶级变量不是全局范围的,在 CoffeeScript 中返回值是强制性的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:顶级变量不是全局范围的,在 CoffeeScript 中返回值是强制性的
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
基础教程推荐
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06