31May

Getters and Setters in Coffee on NodeJS

Posted by Elf Sternberg as Uncategorized

I can’t claim ownership of this, only the refinement of using Coffee’s native prototype specifier.  But it’s a sweet, sweet way of creating a getter/setter pair in a coffeescript class:

Function::define = (prop, desc) ->
    Object.defineProperty this::, prop, desc

class CheckThisOut
    _fld1: null
    constructor: (@_fld1 = {}) ->

    @define 'field'
        get: -> @_fld1
        set: (v) -> @_fld1 = v

x = new CheckThisOut()
x.field = 5
console.log(x.field)

@define is now a class-level function that creates a new field on a new object, and decorates it with get()/set(). About the only annoying factor here is the need to define the name of the new field in quotes, because that’s what defineProperty() requires, but for a lot of what I do, this is excellent stuff.

In fact, it’s so excellent, I’m surprised an entire ORM hasn’t been written around it yet.

2 Responses to Getters and Setters in Coffee on NodeJS

Property in CoffeeScript - nonocast

March 12th, 2013 at 11:41 am

[…] Getters and Setters in Coffee on NodeJS by Elf Sternberg […]

Elf Sternberg

March 12th, 2013 at 12:37 pm

The follow-on link to this is interesting, too, especially the Declarative Model Syntax in Coffeescript. I wonder if it could be extended with Bacon.js to get that beautiful hybridized reactor pattern working? Hmm…

Comment Form

Subscribe to Feed

Categories

Calendar

May 2012
M T W T F S S
« Apr   Jun »
 123456
78910111213
14151617181920
21222324252627
28293031