GitHub上好多项目都是用coffee-script写的,尤其是运行于Nodejs下的项目,也没太在意,一直没有仔细看看coffee。我学习编程主要还是兴趣驱动,我之前对OT(google wave,etherpad等实时编辑器的核心)很感兴趣,这个项目ShareJs,用coffee实现了类似etherpad的功能,我要看代码,必须了解下coffee了
1.coffee-script在线测试
如果安装了Nodejs,直接在命令行下面跑最好了,这里提供了一个简单的线上测试环境
http://jashkenas.github.com/coffee-script/ 单击TRY COFFEESCRIPT
2.语法
coffee最终是转化为js执行的,不去关注转化后的代码,那么如何写coffee-script呢?
函数定义:
hi = (a,b) ->
alert(a+" say to:"+b+",hello!");
右边会自动生成编译后真正执行的javascript(后面不再列出)
var hi;
hi = function(a, b) {
return alert(a + " say to:" + b + ",hello!");
};
函数调用:不用括号
hi "tom","Lily"
字符
内插字符:
name = "tom"
s = "hi #{name}"
alert name
/*跨越多行的字符,类似Python的语法*/
name = "tom
,john
,kinas
"
s = "hi #{name}"
alert name
定义数组
a = [1,2,3,4];/*第一种方法定义*/
b = [ i for i in [1..10]];/*第二种方法,用 ‘..’ 表示范围*/
alert a;
alert b;
遍历数组
a = [1,2,3,4];
b = [ i for i in a];/*很自然的遍历方式*/
alert b;
还可以调用函数:
[alert i for i in a]
this:在coffe没有显示的this,@代替之
sayHello (name)->
@name = name
@say -> alert name
对应的javascript:
sayHello(function(name) {
this.name = name;
return this.say(function() {
return alert(name);
});
});
一行函数调用,带判断
alert "I knew it!" if elvis?
coffee-script 的继承(摘自这里)
class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved " + meters + "m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
观察生成的javascript,可以窥探其继承的实现
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
Animal = (function() {
function Animal(name) {
this.name = name;
}
Animal.prototype.move = function(meters) {
return alert(this.name + " moved " + meters + "m.");
};
return Animal;
})();
Snake = (function() {
__extends(Snake, Animal);
function Snake() {
Snake.__super__.constructor.apply(this, arguments);
}
Snake.prototype.move = function() {
alert("Slithering...");
return Snake.__super__.move.call(this, 5);
};
return Snake;
})();