Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript: Using instanceof vs Class.constructor.name

Tags:

coffeescript

If I have a class:

class Haha
  constructor: (@lolAmount = 1) ->
    alert @lolAmount

And I want to check if an object is of the right class, Is it always safe to use constructor.name:

haha = new Haha()
unless haha.constructor.name is 'Haha'
  throw Error 'Wrong type'

or is it better to use instanceof:

haha = new Haha()
unless haha instanceof Haha
  throw Error 'Wrong type'

One argument I have for instanceof is when using extends:

class BigHaha extends Haha

bigHaha = new BigHaha
console.log bigHaha instanceof Haha #true

but how safe is it, being a JavaScript operator - I feel like I should be sceptical about it.

On the other hand, with constructor.name it is very clear what is happening. Is it guaranteed that constructor.name will be set on all objects?

Thanks for any info.

like image 447
phenomnomnominal Avatar asked Jul 27 '12 15:07

phenomnomnominal


1 Answers

First of all, constructor is also straight JavaScript:

Returns a reference to the Object function that created the instance's prototype.

So when you say o.constructor, you're really doing straight JavaScript, the name constructor for the CoffeeScript object initialization function is a separate matter.

So now you have a choice between using JavaScript's constructor property or JavaScript's instanceof operator. The constructor just tells you what "class" was used to create the object, instanceof on the other hand:

[...] tests whether an object has in its prototype chain the prototype property of a constructor.

So instanceof is the right choice if you want to allow for subclassing.

like image 171
mu is too short Avatar answered Oct 24 '22 11:10

mu is too short