Skip to content

Instantly share code, notes, and snippets.

@hackugyo
Created August 6, 2012 04:08
Show Gist options
  • Save hackugyo/3270167 to your computer and use it in GitHub Desktop.
Save hackugyo/3270167 to your computer and use it in GitHub Desktop.
Private Method accessing to static property in CoffeeScript
# http://d.hatena.ne.jp/keyesberry/20110908/p1
# 上でプライベートメソッドがうまく定義できなかった理由を,
# http://d.hatena.ne.jp/yogit/20110921/1316592709
# から探る
# あと,こちらも
# http://sucrose.hatenablog.com/entry/20120229/p1
class Duck
constructor: (@name, @age) ->
# 今回の結論.
# プライベートメソッドで静的プロパティにアクセスしたければ,コンストラクタ内でメソッド定義する
@food_private_in_constructor = ->
"#{@age} beans"
eat: ->
alert "eat " + @food_private_in_constructor()
food: ->
"#{@age} beans"
food_with_fat: =>
"#{@age} beans"
###
# コンストラクタ外で記述するとthisの範囲がかわってしまうので,インスタンス変数にアクセスできない
# food_private = ->
# "#{@age} beans"
###
###
# fatarrowを使ってもだめ, Duck.ageではなくDuck.prototype.ageにアクセスしたいので
# food_private_with_fat = =>
# "#{@age} beans"
###
###
# これもだめ.けっきょくageのスコープがつかまえられない.
# food_private_with_prototype_and_fat = =>
# "#{this.prototype.age} beans"
###
mofi = new Duck('Mofi', 12)
mofi.eat() # => 'eat undefined beans'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment