CoffeeScript:使用instanceof vs Class.constructor.name [英] CoffeeScript: Using instanceof vs Class.constructor.name

查看:172
本文介绍了CoffeeScript:使用instanceof vs Class.constructor.name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类:

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

我想检查一个对象是否是正确的类,使用 constructor.name 始终是安全的:

  haha​​ = new Haha()
,除非haha.constructor.name是'Haha'
throw错误'错误类型'

或者最好使用 instanceof

  haha​​ = new Haha()
,除非haha instanceof Haha
throw错误'错误类型'


$ b b

我使用 instanceof 的一个参数是使用 extends 时:

  class BigHaha extends Haha 

bigHaha = new BigHaha
console.log bigHaha Haha的实例#true

但是它是多么安全,作为一个JavaScript操作符 - 我觉得我应该怀疑它。



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



感谢任何信息。 >

解决方案

首先, 构造函数 也是正确的JavaScript:


返回对创建实例原型的Object函数的引用。


> o.constructor ,你真的做直接的JavaScript,CoffeeScript对象初始化函数的名称构造函数是一个单独的事情。



现在你可以选择使用JavaScript的构造函数属性或JavaScript的 instanceof 运算符。 构造函数只是告诉你用什么类来创建对象,

$

b $ b

[...]测试一个对象在其原型链中是否具有构造函数的原型属性。


< blockquote>

所以 instanceof 是正确的选择,如果你想允许子类化。


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.

这篇关于CoffeeScript:使用instanceof vs Class.constructor.name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆