本文介绍了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: > o.constructor ,你真的做直接的JavaScript,CoffeeScript对象初始化函数的名称构造函数是一个单独的事情。 现在你可以选择使用JavaScript的构造函数属性或JavaScript的 instanceof 运算符。 构造函数只是告诉你用什么类来创建对象,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:So instanceof is the right choice if you want to allow for subclassing. 这篇关于CoffeeScript:使用instanceof vs Class.constructor.name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-20 13:09