在coffeescript中测试类成员资格的最简单方法是什么? [英] What is the easiest way to test for class membership in coffeescript?
问题描述
我正在寻找一个等价的Ruby的blah.is_a?(String)
of Objective-C的 [@blahisKindOfClass :[NSString class]]
I'm looking for an equivalent of Ruby's "blah".is_a?(String)
of Objective-C's [@"blah" isKindOfClass:[NSString class]]
推荐答案
你想测试一个对象是否来自特殊类?然后,您需要 instanceof
关键字。 (它不是由CoffeeScript添加的东西,而是JavaScript的一部分。)CoffeeScript类被设置为,如果你写
Do you want to test whether an object is descended from a particular class? Then you want the instanceof
keyword. (It's not something added by CoffeeScript; it's a part of JavaScript.) CoffeeScript classes are set up so that if you write
class A
class B extends A
class C extends B
true:
(new A) instanceof A
(new B) instanceof B and (new B) instanceof A
(new C) instanceof C and (new C) instanceof B and (new C) instanceof A
另外,任何对象将返回 true for
instanceof Object
。
Also, any object will return true
for instanceof Object
.
如果要测试对象是其实例的特定类,请使用 .constructor
。例如,
If you want to test the specific class that an object is an instance of, use .constructor
. For instance,
(new B).constructor is B
或如果您要使用字符串,
or if you'd like to use a string,
(new B).constructor.name is 'B'
这篇关于在coffeescript中测试类成员资格的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!