npm install -g coffee-script
# watch and compile
coffee -w --output lib --compile src
//
coffee -w -c index.coffee
CoffeeScript在编译时为每条语句加上;
CoffeeScript中的注释采用#
target = "world"
alert "hello, #{target}" //注意双引号
alert "hello" + target
object1 = one: 1, two: 2
object2 =
one: 1
two: 2
arr1 = [1, 2]
arr2 = [
1,
2
]
obj = {a:"foo", b:"bar"}
{a, b} = obj
arr = [1, 2]
[a, b] = arr
numbers = [0..9] //两个或三个点号
numbers[3..5] = [-3,-4,-5] //替换number 3-5的值;可以是任意个数
my = "my string"[0..1]
arr = ["foo", "bar"]
"foo" in arr
for name, i in ["roger", "roderick"]
alert "#{i} - Release #{name}"
items = ["ranger", "roderick", "brian"]
alert 'ok' for item in items when item is "ranger"
items = [{id: 0, name: "ranger"}, {id: 1, name: "roderick"}, {id: 2, name: "brian"}]
result = (item for item in items when item.id is 1) //注意前面有个item;以数组形式返回
sum = (nums) ->
nums.reduce(x, y) -> x + y
sum 1,2,3
//
(function() {
var sum;
sum = function(nums) {
return nums.reduce(x, y)(function() {
return x + y;
});
};
sum(1, 2, 3);
}).call(this);
times = (a = 1, b = 2) -> a * b
CoffeeScript的函数调用可以不用()语法包围参数,像ruby一样跟在函数名后面就可以,不过这也有时候会带来问题,特别是没有参数的调用
缩进的格式有时需要小心,比如用多个函数做参数的时候
$(".toggle").toggle ->
"on"
, ->
"off"
//
(function() {
$(".toggle").toggle(function() {
return "on";
}, function() {
return "off";
});
}).call(this);