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
Just change the ==
to instanceof
if(cat instanceof Cat)
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With