CoffeeScript クラスの変数とメソッドの定義方法まとめ


CoffeeScriptのクラスまわりのシンタックスが分かりづらすぎるのでまとめました。
privateなインスタンス変数・メソッドは未実装なようです。悲しい。
protectedなんて勿論ありません。

メソッド

インスタンスメソッド(publicのみ)

hoge.coffee
class Hoge
    hello: -> console.log('hello')

a = new Hoge()
a.hello()

クラスメソッド

public

二種類の定義方法がある。

hoge.coffee
class Hoge
    @hello: -> console.log('hello')
    @hi = -> console.log('hi')

Hoge.hello()
Hoge.hi()

private

hoge.coffee
class Hoge
    hello = -> console.log('hello')
    @moge: -> hello()
    piyo: -> hello()

変数

インスタンス変数(publicのみ)

三種類の定義方法がある。

hoge.coffee
class Hoge
    x: 10
    constructor: (@y) -> @z = 30
    print: -> console.log(@x)

a = new Hoge(20)
console.log(a.x)

クラス変数

public

二種類の定義方法がある。

hoge.coffee
class Hoge
    @x = 10
    @y: 20
    @printClass: -> console.log(Hoge.x)
    printInstance: -> console.log(Hoge.x)

console.log(Hoge.x)

private

hoge.coffee
class Hoge
    x = 10
    @printClass: -> console.log(x)
    printInstance: -> console.log(x)

参考

http://memo.devjam.net/clip/943
http://memo.devjam.net/clip/983
http://qiita.com/mm-git/items/ced8482a41cd070c245a