在咖啡脚本中测试班级成员资格的最简单方法是什么? [英] What is the easiest way to test for class membership in coffeescript?

查看:22
本文介绍了在咖啡脚本中测试班级成员资格的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找与 Ruby 的 "blah".is_a?(String) 等效的 Objective-C 的 [@"blah" isKindOfClass:[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

那么以下是正确的:

(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

此外,任何对象都会为 instanceof Object 返回 true.

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'

这篇关于在咖啡脚本中测试班级成员资格的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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