CoffeeScriptだと、簡潔に(=短く)書けるからアルゴリズムや実装に集中できますね。
enchant.jsでさくっとアルゴリズミックなゲームを作る時なんかに良さそうです。
PythonやRubyの書き方のようなイメージになります。
基本
1、インデントが意味を持つかわりに、カッコが不要
2、行末セミコロンが不要
3、varでの宣言が不要(自動で宣言される→グローバル変数生成防止)
for文
iを使えるfor文が.lengthとiを使ういつものやつになります。
# iを使えるfor文 arr = ["zero", "one", "two"] for val, i in arr console.log "#{i}: #{val}" # 0:one 1:one 2:two # foreach arr = ["one","two","three","four"] for num in arr console.log num #one two three four # 数字はこちら arr = [1,2,3,4,5,6,7] for i in [0..6] console.log arr[i] #1,2,3,4,5,6,7
関数
最後の変数が自動的にreturnされるのがポイント
# 引数なし func = -> "bar" # 引数あり times = (a, b) -> a * b console.log func() # bar console.log times(2,4) # 8
if文
then , is , isnt , and ,or をよく使いそう。複合するときは注意
num = 15 foo = "15" if num is foo console.log "foo" else if num isnt 15 console.log "not 10" else if num is 10 and 15 console.log "contradiction" else if num is 10 or 15 alert "mankind" # 結果は「mankind」 if num is 15 then alert "mankind" # 結果は「mankind」 #複合のif分 i = 1 b = 1 if i is 0 or b is 2 console.log "match" else console.log "no" # no
後置if
JSコードが後から生成されるので文法が変とかはひとまず考えない
num = 3 console.log "ok" if num is 3
クラス
変数のスコープ、継承(extendsでOK)など、詳しく知るならこちら
class Human constructor: (name) -> @name = name eyes:2 checkEyes: => alert "目は#{@eyes}つ" Bob = new Human("Bob") Bob.checkEyes() # 目は2つ Bob.eyes = 1 Bob.checkEyes() # 目は1つ
jQuery
非常に書きやすいです
$ -> $('#hoge').val("") #とか $('#foo').click -> $('#hoge').val("")
コメント
## 1行コメント ### 複数行コメント ###
配列 → 角括弧[]は必須
Arr = [1, 2, 3] Arr = [ 1 2 3 ] Arr = [1,2,3,] Arr = [1..100] # 1から100
オブジェクト(連想配列)
改行がセミコロン扱い、カッコはインデントで表現
fruit = [ apple color:red yummy:true dorian color:green yummy:false ]
while , until
saifu = 100 price = 10 buy = (price,saifu) -> saifu - price buy(price,saifu) while saifu > 0
Switch, When, Else
saifu = 1000; switch saifu when 0 then alert "no" when 1 then alert "1$" when 2 then alert "2$" else alert "okay" #okay
高階関数
たとえばsetTImeout(func,time)とか
setTimeout -> console.log "foo" , 100
主な情報元
CoffeeScript公式
The Little Book on CoffeeScript
http://minghai.github.io/library/coffeescript/index.html
ドットインストールのCoffeeScript入門
http://dotinstall.com/lessons/basic_coffeescript