Skip to content

Instantly share code, notes, and snippets.

@davepeck
Created December 7, 2012 21:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davepeck/4236746 to your computer and use it in GitHub Desktop.
Save davepeck/4236746 to your computer and use it in GitHub Desktop.
ES5 properties and coffee script
Function::property = (prop, desc) ->
Object.defineProperty this.prototype, prop, desc
class Foo
@property 'neat'
get: ->
42
class Bar extends Foo
@property 'neat'
get: ->
super
# 42
alert(new Foo().neat)
# exception
alert(new Bar().neat)
Function::property = (prop, desc) ->
Object.defineProperty this.prototype, prop, desc
class Foo
@property 'neat'
get: ->
42
class Bar extends Foo
@property 'neat'
get: ->
Bar.__super__.neat
# 42
alert(new Foo().neat)
# 42
alert(new Bar().neat)
@ben-x9
Copy link

ben-x9 commented Jul 25, 2015

Better setup (non-enumerable)

Object.defineProperty Function.prototype, 'get',
  configurable: yes
  writable: yes
  value: (prop, get) ->
    Object.defineProperty @prototype, prop, {get}

Object.defineProperty Function.prototype, 'set',
  configurable: yes
  writable: yes
  value: (prop, set) ->
    Object.defineProperty @prototype, prop, {set}

Object.defineProperty Object.prototype, 'getSuper',
  configurable: yes
  writable: yes
  value: (prop) ->
    (Object.getOwnPropertyDescriptor @constructor.__super__, prop).get.apply @

Object.defineProperty Object.prototype, 'setSuper',
  configurable: yes
  writable: yes
  value: (prop) ->
    (Object.getOwnPropertyDescriptor @constructor.__super__, prop).set.apply @

@Asc2011
Copy link

Asc2011 commented Jul 27, 2016

Hi all and thx for the example(s),

@ben-x9:
It works with setters when one changes the getter-definition

Object.defineProperty Function.prototype, 'get',
  configurable: yes
  writable: yes
  value: (prop, get) ->
    Object.defineProperty @prototype, prop, {
     get: get
     configurable: yes
     writable: yes
   }

to allow a following setter-definition. The code as-is throws 'Cannot redefine property ' in Chrome.

cheers, Andreas

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