CoffeeScript是逐句編譯為JavaScript的一種小型語言,且沒有運作時的解釋器。 作為JavaScript的替代品之一,CoffeeScript旨在編譯人類可讀、美觀優雅且速度不輸原生的代碼, 且編譯後的代碼可以在任何JavaScript運作時正确運作。
參閱
CoffeeScript官方網站以擷取CoffeeScript的完整教程。
CoffeeScript是一種很潮的程式設計語言,它緊随衆多現代程式設計語言的趨勢。 是以正如Ruby和Python,CoffeeScript使用井号标記注釋。
# 這是注釋
###
大段落注釋以此為例,可以被直接編譯為 '/ *' 和 '* /' 包裹的JavaScript代碼。
在繼續之前你需要了解JavaScript的基本概念。
示例中 => 後為編譯後的JavaScript代碼
指派
number = 42 #=> var number = 42;
opposite = true #=> var opposite = true;
條件
number = -42 if opposite #=> if(opposite) { number = -42; }
函數
square = (x) -> x * x #=> var square = function(x) { return x * x; }
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
#=>var fill;
#
#fill = function(container, liquid) {
# if (liquid == null) {
# liquid = "coffee";
# }
# return "Filling the " + container + " with " + liquid + "...";
#};
區間
list = [1..5] #=> var list = [1, 2, 3, 4, 5];
對象
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
#=> var math = {
# "root": Math.sqrt,
# "square": square,
# "cube": function(x) { return x * square(x); }
#}
Splats
race = (winner, runners...) ->
print winner, runners
#=>race = function() {
# var runners, winner;
# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
# return print(winner, runners);
存在判斷
alert "I knew it!" if elvis?
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
數組推導
cubes = (math.cube num for num in list)
#=>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;
# })();
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
#=>foods = ['broccoli', 'spinach', 'chocolate'];
#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
# food = foods[_k];
# if (food !== 'chocolate') {
# eat(food);