gpt4 book ai didi

CoffeeScript:使用 instanceof 与 Class.constructor.name

转载 作者:行者123 更新时间:2023-12-04 00:50:44 24 4
gpt4 key购买 nike

如果我有一个类:

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 运算符(operator)它有多安全 - 我觉得我应该对此持怀疑态度。

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

感谢您提供任何信息。

最佳答案

首先, constructor 也是直接的 JavaScript:

Returns a reference to the Object function that created the instance's prototype.



所以当你说 o.constructor ,你真的在​​做直接的 JavaScript,名字 constructor对于 CoffeeScript 对象的初始化函数是另外一回事。

所以现在你可以选择使用 JavaScript 的 constructor属性或 JavaScript 的 instanceof运营商。 constructor只是告诉你用什么“类”来创建对象, instanceof 另一方面:

[...] tests whether an object has in its prototype chain the prototype property of a constructor.



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

关于CoffeeScript:使用 instanceof 与 Class.constructor.name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11690894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com