Skip to content

Instantly share code, notes, and snippets.

@darkoverlordofdata
Last active December 11, 2015 23:29
Show Gist options
  • Save darkoverlordofdata/4677206 to your computer and use it in GitHub Desktop.
Save darkoverlordofdata/4677206 to your computer and use it in GitHub Desktop.
Subclassing getters and setters in coffee-script
Function::get = ($def) ->
$name = Object.keys($def)[0]
Object.defineProperty @::, $name, {get: $def[$name], configurable: yes}
class HeartOfGold
_answer: 0
@get answer: -> @_answer
@set answer: (value) -> @_answer = value
Function::set = ($def) ->
$name = Object.keys($def)[0]
Object.defineProperty @::, $name, {set: $def[$name], configurable: yes}
class Zaphod extends HeartOfGold
# Explicit access to super is used to access property behavior
@get answer: -> Zaphod.__super__.answer * 2 * Math.PI
@set answer: (value) -> Zaphod.__super__.answer = value
constructor: (value) ->
@answer = value
meaning_of_life = new Zaphod(6.684507609859605)
console.log "Zaphod says that the meaning of life, the universe, and everything is "+meaning_of_life.answer
###
$ coffee heartofgold
Zaphod says that the meaning of life, the universe, and everything is 42
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment