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.
First of all,
constructoris also straight JavaScript:So when you say
o.constructor, you’re really doing straight JavaScript, the nameconstructorfor the CoffeeScript object initialization function is a separate matter.So now you have a choice between using JavaScript’s
constructorproperty or JavaScript’sinstanceofoperator. Theconstructorjust tells you what “class” was used to create the object,instanceofon the other hand:So
instanceofis the right choice if you want to allow for subclassing.