Skip to content

Instantly share code, notes, and snippets.

@michaelsbradleyjr
Created September 17, 2011 05:02
Show Gist options
  • Save michaelsbradleyjr/1223649 to your computer and use it in GitHub Desktop.
Save michaelsbradleyjr/1223649 to your computer and use it in GitHub Desktop.
classof for CoffeeScript
## ----- classof.coffee ----- ##
_classof = (o) ->
if o is null
'Null'
else if o is undefined
'Undefined'
else
Object.prototype.toString.call(o).slice(8,-1)
module.exports = classof = (o) ->
klass = _classof(o)
if klass in ['Null', 'Undefined', 'Window']
klass
else
Klass = eval(klass)
if o.toString is Klass.prototype.toString
klass
else
o.toString().slice(8,-1)
## ----- Now load it as a module ----- ##
classof = require './classof'
class MyClass
getFnName: (fn) ->
fn.name or fn.toString().match(/function\s*([^(]*)\(/)[1]
toString: -> '[object ' + @getFnName(@constructor) + ']'
class Other extends MyClass
class Another extends Other
hiThere = new Another
classof hiThere is 'Another' # true
class YetAnother extends Another
constructor: (@someprop) ->
@initialize()
initialize: ->
if (classof @someprop) isnt 'MyClass' then throw 'an error' # I'm requiring @someprop to be an instance of MyClass
inst1 = new YetAnother [] # throws an error
inst2 = new YetAnother (new MyClass) # works okay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment