Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class type in CoffeeScript

Tags:

coffeescript

How can I find that class of an object once it has been instantiated?

class Cat
  constructor: (@name) ->

class Dog
  constructor: (@name) ->

cat = new Cat "Kitty"
dog = new Dog "Doggy"

if (cat == Cat)  <- I want to do something like this
like image 426
Alexis Avatar asked Mar 01 '12 22:03

Alexis


4 Answers

Just change the == to instanceof

if(cat instanceof Cat)
like image 106
Sandro Avatar answered Oct 19 '22 20:10

Sandro


If you wanted to know the type name of a particular object (which is what I was just looking for when I found this question), you can use the syntax {object}.constructor.name

for example

class Cat
    constructor: (@name) ->

  class Dog
    constructor: (@name) ->

  cat = new Cat()
  dog = new Dog()

  console.log cat.constructor.name
  console.log dog.constructor.name

which will output

Cat
Dog
like image 34
Dinis Cruz Avatar answered Oct 19 '22 20:10

Dinis Cruz


The way to do this is to check the type of an object using either

instanceof

or

typeof

i.e.

if (obj instanceof Awesomeness){
//doSomethingCrazy();
}

Just as in JavaScript, Coffee Script does not provide any abstraction over these functions

like image 37
Cory Dolphin Avatar answered Oct 19 '22 18:10

Cory Dolphin


AFAIU, the general solution would be using @constructor - Useful when you don't know or don't want to specify the class name.

There was even a discussion regarding making @@ a shortcut for it.

like image 29
m0she Avatar answered Oct 19 '22 18:10

m0she