Created
August 6, 2012 04:08
-
-
Save hackugyo/3270167 to your computer and use it in GitHub Desktop.
Private Method accessing to static property in CoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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