CoffeeScript是一门编译到JavaScript的小巧语言。CoffeeScript尝试用简洁的方式展示JavaScript优秀的部分。创建者Jeremy Ashkenas戏称它是JavaScript 的不那么铺张的小兄弟。
CoffeeScript就是将代码一一对应编译到JavaScript,当然了它仅仅是编译到JavaScript,不会在编译过程中执行JavaScript代码的。
CoffeeScript语法简洁,类似Ruby。基本原则就是用更少的代码实现更多的功能。编译过后的代码执行速度只会跟我们用JavaScript编写的代码一样快或者更快,大家不用担心执行速度的问题。
编译前:
# 赋值:
number = 42
opposite = true
# 条件:
number = -42 if opposite
# 函数:
square = (x) -> x * x
# 数组:
list = [1, 2, 3, 4, 5]
# 对象:
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
# Splats:
race = (winner, runners...) ->
print winner, runners
# 存在性:
alert "I knew it!" if elvis?
# 数组 推导(comprehensions):
cubes = (math.cube num for num in list)
编译后:
var cubes, list, math, num, number, opposite, race, square,
__slice = [].slice;
number = 42;
opposite = true;
if (opposite) {
number = -42;
}
square = function(x) {
return x * x;
};
list = [1, 2, 3, 4, 5];
math = {
root: Math.sqrt,
square: square,
cube: function(x) {
return x * square(x);
}
};
race = function() {
var runners, winner;
winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return print(winner, runners);
};
if (typeof elvis !== "undefined" && elvis !== null) {
alert("I knew it!");
}
cubes = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = list.length; _i < _len; _i++) {
num = list[_i];
_results.push(math.cube(num));
}
return _results;
})();