Last active
December 11, 2015 23:29
-
-
Save darkoverlordofdata/4677206 to your computer and use it in GitHub Desktop.
Subclassing getters and setters in coffee-script
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
Function::get = ($def) -> | |
$name = Object.keys($def)[0] | |
Object.defineProperty @::, $name, {get: $def[$name], configurable: yes} |
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
class HeartOfGold | |
_answer: 0 | |
@get answer: -> @_answer | |
@set answer: (value) -> @_answer = value | |
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
Function::set = ($def) -> | |
$name = Object.keys($def)[0] | |
Object.defineProperty @::, $name, {set: $def[$name], configurable: yes} |
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
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