Skip to content

Instantly share code, notes, and snippets.

@vilcans
Created October 9, 2012 14:27
Show Gist options
  • Save vilcans/3859169 to your computer and use it in GitHub Desktop.
Save vilcans/3859169 to your computer and use it in GitHub Desktop.
Properties in CoffeeScript
# 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