18

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
Alexis
  • 23,545
  • 19
  • 104
  • 143

4 Answers4

29

Just change the == to instanceof

if(cat instanceof Cat)
Sandro
  • 4,761
  • 1
  • 34
  • 41
  • thanks for the specific code help. It will help me with my project in figuring out the object type in an array. – Alexis Mar 01 '12 at 23:04
  • is there a way though to get the name of the object with guessing and checking? – Alexis Mar 01 '12 at 23:10
  • http://stackoverflow.com/questions/7087712/get-the-model-type-for-a-passed-in-backbone-js-model-instance – sye May 04 '12 at 05:44
  • Actually this question might be helpful as well. For some reason I never saw your comment @AlexisK http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript – Sandro May 04 '12 at 15:16
  • From the response in the question above, the equivalent CoffeeScript could be: http://jsfiddle.net/SLtTs/ – Sandro May 04 '12 at 15:22
7

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
edgerunner
  • 14,873
  • 2
  • 57
  • 69
Dinis Cruz
  • 4,161
  • 2
  • 31
  • 49
5

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

Cory Dolphin
  • 2,650
  • 1
  • 20
  • 30
2

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.

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
m0she
  • 444
  • 1
  • 4
  • 9