Created
September 17, 2011 05:02
-
-
Save michaelsbradleyjr/1223649 to your computer and use it in GitHub Desktop.
classof for CoffeeScript
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
## ----- 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