Created
October 9, 2012 14:27
-
-
Save vilcans/3859169 to your computer and use it in GitHub Desktop.
Properties in CoffeeScript
This file contains 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
# Create a convenient property creator function | |
Function::property = (properties) -> | |
for name, descriptor of properties | |
Object.defineProperty @prototype, name, descriptor | |
return | |
# Usage example: | |
class Circle | |
constructor: (@radius) -> | |
@property area: | |
get: -> @radius * @radius * Math.PI | |
set: (a) -> @radius = Math.sqrt(a / Math.PI) | |
window.c = new Circle(10) | |
console.assert c.area == 100 * Math.PI | |
c.area = 1000 | |
console.assert c.area == 1000 | |
console.assert c.radius == Math.sqrt(1000 / Math.PI) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment