12

如果我有一堂课:

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

我想检查一个对象是否属于正确的类,使用是否总是安全的constructor.name

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

还是更好地使用instanceof

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

我的一个论点instanceof是使用时extends

class BigHaha extends Haha

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

但是,作为一个 JavaScript 操作员,它有多安全——我觉得我应该对此持怀疑态度。

另一方面,constructor.name很清楚正在发生什么。是否保证constructor.name将在所有对象上设置?

感谢您提供任何信息。

4

1 回答 1

17

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.

于 2012-07-27T15:52:22.480 回答