CoffeeScript: Using instanceof vs Class.constructor.name

后端 未结 1 1486
醉梦人生
醉梦人生 2020-12-30 07:33

If I have a class:

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

And I want to check if an object is of the right c

相关标签:
1条回答
  • 2020-12-30 07:52

    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.

    0 讨论(0)
提交回复
热议问题