CoffeeScript:使用 instanceof 与 Class.constructor.name [英] CoffeeScript: Using instanceof vs Class.constructor.name
问题描述
如果我有课:
class Haha
constructor: (@lolAmount = 1) ->
alert @lolAmount
我想检查一个对象是否属于正确的类,使用 constructor.name
是否总是安全的:
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'
还是使用 instanceof
更好:
haha = new Haha()
unless haha instanceof Haha
throw Error 'Wrong type'
我对 instanceof
的一个论点是在使用 extends
时:
One argument I have for instanceof
is when using extends
:
class BigHaha extends Haha
bigHaha = new BigHaha
console.log bigHaha instanceof Haha #true
但作为一名 JavaScript 操作员,它有多安全 - 我觉得我应该对此持怀疑态度.
but how safe is it, being a JavaScript operator - I feel like I should be sceptical about it.
另一方面,使用 constructor.name
很清楚发生了什么.是否保证 constructor.name
将在所有对象上设置?
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?
感谢您提供任何信息.
推荐答案
首先,constructor
也是直接的 JavaScript:
First of all, constructor
is also straight JavaScript:
返回对创建实例原型的 Object 函数的引用.
Returns a reference to the Object function that created the instance's prototype.
所以当你说 o.constructor
时,你实际上是在做直接的 JavaScript,CoffeeScript 对象初始化函数的名称 constructor
是另一回事.
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.
所以现在您可以选择使用 JavaScript 的 constructor
属性或 JavaScript 的 instanceof
运算符.constructor
只是告诉你使用什么类"来创建对象,instanceof
另一方面:
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:
[...] 测试对象的原型链中是否具有构造函数的 prototype
属性.
[...] tests whether an object has in its prototype chain the
prototype
property of a constructor.
如果你想允许子类化,instanceof
是正确的选择.
So instanceof
is the right choice if you want to allow for subclassing.
这篇关于CoffeeScript:使用 instanceof 与 Class.constructor.name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!