Skip to content

Instantly share code, notes, and snippets.

@DomiR
Forked from alexaivars/setter_pattern.coffee
Created June 3, 2014 09:14
Show Gist options
  • Save DomiR/1551c3779da16c1a42b9 to your computer and use it in GitHub Desktop.
Save DomiR/1551c3779da16c1a42b9 to your computer and use it in GitHub Desktop.
Function::define = (prop, desc) ->
Object.defineProperty this.prototype, prop, desc
class GetterSetterTest
constructor: (@_obj = {}) ->
# 'obj' is defined via the prototype, the definition proxied through
# to 'Object.defineProperty' via a function called 'define' providing
# some nice syntactic sugar. Remember, the value of '@' is
# GetterSetterTest itself when used in the body of it's class definition.
@define 'obj'
get: ->
return @_obj
set: (value) ->
@_obj = value
_obj: null
@DomiR
Copy link
Author

DomiR commented Jun 3, 2014

Here's another approach for defining properties with getters and setters in CoffeeScript that maintains a relatively clean syntax without adding anything to the global Function prototype (which I'd rather not do):

class Person
  constructor: (@firstName, @lastName) ->
  Object.defineProperties @prototype,
    fullName:
      get: -> "#{@firstName} #{@lastName}"
      set: (name) -> [@firstName, @lastName] = name.split ' '

p = new Person 'Robert', 'Paulson'
console.log p.fullName # Robert Paulson
p.fullName = 'Space Monkey'
console.log p.lastName # Monkey

It works well with many properties. For example, here's a Rectangle class that is defined in terms of (x, y, width, height), but provides accessors for an alternative representation (x1, y1, x2, y2):

class Rectangle                                     
  constructor: (@x, @y, @w, @h) ->
  Object.defineProperties @prototype,
    x1:
      get: -> @x
      set: (@x) ->
    x2:
      get: -> @x + @w
      set: (x2) -> @w = x2 - @x
    y1:
      get: -> @y
      set: (@y) ->
    y2:
      get: -> @y + @h
      set: (y2) -> @w = y2 - @y

r = new Rectangle 5, 6, 10, 11
console.log r.x2 # 15

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment