我只是开始使用Coffeescript脚本,然后运行“在CoffeeScript中编程”一书中介绍的示例。
在while循环部分,我对为什么对times函数的调用必须声明如下所述很感兴趣。
times = (number_of_times, callback) ->
index = 0
while index++ < number_of_times
callback(index)
return null
times 5, (index) ->
console.log index
我在阅读代码时有点困难,当我尝试的时候:
tim
我的第一个测试是在普通的JavaScript中进行的,然后我想尝试用CoffeeScript编写相同的测试。
括号不是我想要的,这导致了测试失败.我得到的错误是:TypeError: Object 1.00 has no method 'toBe'
我的工作JavaScript测试如下:
describe( "conversion from water to coffee", function () {
it("converts water to coffee", function () {
expect(waterToCof
我发现了一些奇怪的coffeescript编译行为,试图确定它是否是预期的(如果是,为什么)。
此代码:
bob = 'test'
bobslash = bob +'/'
汇编成:
var bob, bobslash;
bob = 'test';
bobslash = bob(+'/');
而不是预期的:
var bob, bobslash;
bob = 'test';
bobslash = bob + '/';
注意,在第一个coffeescript中,+和'\'之间缺少空间。添加
我刚才正在写一些CoffeeScript,并得到了一个奇怪的错误:
TypeError: Thing(param) is not a constructor
但它是!当我在控制台里试一试:
var that = new Thing(param);
that.doesSomething();
经过一些混乱之后,我查看了编译后的源代码,发现coffee将that = new Thing param编译成that = new(Thing(param));。奇怪,我以前从没见过。所以我立即试了一试:还有塔达!现在我可以复制:
var that = new(Thing(param));
that.pre
我正在用CoffeeScript和Rails做一个新的项目,但是当我用CoffeeScript编写一些类时,我坚持了一些东西。
我正在做以下事情:
# Definition of functions like every, after here...
class Tracker
constructor: ->
@currentTime = 0
@_updateTime(@currentTime)
every 1000, @_countTime.bind @ # Just a shorthand for setInterval
_countTime: -
我正在使用backbone.js,用coffeescript编写它,但是得到了这个错误,并且无法解决它! 代码片段: module.exports = class CoreModel extends Backbone.Model
destroyed: false
# Helper to toggle the state of boolean value (using not)
toggle: (key) -> @swap key, invert
# Helper to change the value of an entry using a functio
为什么需要用Ruby语言编写end分隔符?它不能像Python或CoffeeScript中那样从缩进中解释吗?
class String
COLORS.each do |color,code|
define_method "in_#{color}" do
"<span style=\"color: ##{code}\">#{self}</span>"
end
end
end
在我看来会好得多,因为
class String
COLORS.each do |color,code|
我注意到Coffeescript中的可选括号引入了语法歧义。例如,代码
prompt Math.max(2), 3 # no space after max
编译为
prompt(Math.max(2), 3); // one parameter to max(), two to prompt()
鉴于
prompt Math.max (2), 3 # space after max
编译为
prompt(Math.max(2., 3)); // two parameters to max(), one to prompt()
即,在参数列表之前添加空格改变了参数
我注意到,在CoffeeScript中,如果我使用以下命令定义函数:
a = (c) -> c=1
我只能得到函数表达式
var a;
a = function(c) {
return c = 1;
};
但就我个人而言,我经常使用函数声明,例如:
function a(c) {
return c = 1;
}
我确实使用了第一种形式,但我想知道在CoffeeScript中是否有一种方法可以生成函数声明。如果没有这样的方法,我想知道为什么CoffeeScript会避免这样做。我不认为JSLint会在声明时发出错误,只要函数是在作用域的顶部声明的。