Last active
December 14, 2015 11:19
-
-
Save frostney/5077762 to your computer and use it in GitHub Desktop.
Properties in CoffeeScript without modifying the Function prototype, plus it's also compatible to Codo (https://github.com/netzpirat/codo).
This file contains hidden or 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
do (root = exports ? this) -> | |
'use check' | |
root.ClassHelper = (object) -> | |
objPrototype = object:: | |
methods = | |
property: (prop) -> | |
for key, value of prop | |
propObject = | |
configurable: true, | |
enumerable: false, | |
propObject.get = value.get if value.get? | |
propObject.set = value.set if value.set? | |
Object.defineProperty objPrototype, key, propObject | |
null | |
staticProperty: (prop) -> | |
Object.defineProperty object, key, value for key, value of prop | |
null | |
get: (prop) -> | |
for name, getter of prop | |
obj = {} | |
obj[name] = {get: getter} | |
methods.property obj | |
null | |
set: (prop) -> | |
for name, setter of prop | |
obj = {} | |
obj[name] = {set: setter} | |
methods.property obj | |
null | |
methods |
This file contains hidden or 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
class Person | |
constructor: (@name) -> | |
{get, set} = ClassHelper(@) | |
get age: -> 26 | |
get myname: -> "My name is: #{@name}" | |
set myname: (@name) -> | |
myPerson = new Person('Johannes Stein') | |
console.log myPerson.age | |
myPerson.age = 20 # Well, I feel younger than I am | |
console.log myPerson.age # Still 26 :( | |
console.log myPerson.myname | |
myPerson.myname = 'Stoney' | |
console.log myPerson.myname |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment