CoffeeScript简介
代码从这里CoffeeScript: The beautiful way to write JavaScript抄来的
闲逛博客的时候看到这个东西,以前没听说过,看着挺好玩的,抄点代码,就算是简单介绍吧。
CoffeeScript很小的语言,用好看的方式写js,编译成js代码。项目地址:http://jashkenas.github.com/coffee-script/
The golden rule of CoffeeScript is: "It's just JavaScript".
下面开始抄代码
CoffeeScript code:
square = (x) -> x * x
cube = (x) -> square(x) * x
"Compiled" JavaScript code:
var cube, square;
square = function(x) {
return x * x;
};
cube = function(x) {
return square(x) * x;
};
ajax
CoffeeScript
get: (offset, callback, limit) =>
data =
project_id: Projects.getCurrent().id
limit: limit or @default_limit
if offset
data.offset = Calendar.jsonFormat(offset, true)
@ajax.getArchived(data, (data) =>
if !offset
@setCache(data)
callback(data)
)
js
get: function(offset, callback, limit) {
var self = this;
var data = {
project_id: Projects.getCurrent().id,
limit: limit || this.default_limit
}
if(offset)
data.offset = Calendar.jsonFormat(offset, true);
this.ajax.getArchived(data, function(data) {
if(!offset)
self.setCache(data);
callback(data);
});
},
继承
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved " + meters + "m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
一些特性
生成数组
countdown = (num for num in [10..1])
string interpolation不知道咋翻译,字符串里放变量
author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
多行字符串
mobyDick = "Call me Ishmael. Some years ago -
never mind how long precisely -- having little
or no money in my purse, and nothing particular..."
用@表示this指针
Account = (customer, cart) ->
@customer = customer
@cart = cart
$('.shopping_cart').bind('click', (event) =>
@customer.purchase @cart
)