Skip to content

Instantly share code, notes, and snippets.

@wwalser
Created March 23, 2012 07:24
Show Gist options
  • Save wwalser/2167931 to your computer and use it in GitHub Desktop.
Save wwalser/2167931 to your computer and use it in GitHub Desktop.
Of ninjas and superheroes made mortal again.
console = {}
console.log = (what) ->
alert what
class Person
constructor : (@name) ->
sayName : ->
console.log this.name
getName: ->
this.name
setName:(@name) ->
class Ninja extends Person
getName : ->
'Ninja ' + super
throwStar : ->
console.log(this.getName() + ' threw a ninja star.')
class Super extends Person
getName : ->
'Super ' + super
fly : ->
console.log(this.getName() + ' can fly!');
class Coward
@cowardify: (obj) ->
cowardifyProp = (prop) ->
if prop != 'constructor' and prop.indexOf('get') != 0 and prop.indexOf('set') != 0
obj[prop] = ->
console.log(obj.getName() + ' is too scared to ' + prop);
cowardifyProp prop for prop of obj.constructor::
obj.getName = ->
'Scared ' + obj.name
true
wes = new Person 'Wes'
wes.sayName()
Coward.cowardify wes
wes.sayName()
cal = new Super 'Cal lel'
cal.fly()
Coward.cowardify cal
cal.fly()
barney = new Ninja 'Barney'
barney.throwStar()
Coward.cowardify barney
barney.throwStar()
barney.sayName()
@wwalser
Copy link
Author

wwalser commented Mar 23, 2012

Overall, of Coffeescript, I think I love the syntactic changes. I can't say I'm a fan of the Classical inheritance stuff being thrown in. I get that the penchant for classical inheritance comes from all over when one is first learning Javascript (since nearly every other popular modern language has them), but over time one learns that prototypes are both succinct and more powerful.

cowardify should probably either be a key on an object literal Cowardify or a static method on Person. It's existence is a side effect of my experimenting with the static method syntax after reading further down the Coffeescript docs and wondering how much metaprogramming power is actually extended to them. I was most interested in the code that all of this generates. It's quite nice.

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