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, 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.
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