What is the easiest way to test for class membership in coffeescript?

梦想与她 提交于 2019-12-20 09:55:15

问题


I'm looking for an equivalent of Ruby's "blah".is_a?(String) of Objective-C's [@"blah" isKindOfClass:[NSString class]]


回答1:


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

then the following is 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

Also, any object will return true for instanceof Object.

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'



回答2:


It feels wrong for me to create an instance of a class. You never know, what parameters the constructor might expect.

So what I came up with is this:

class A
class B extends A

console.log B.__super__ is A.prototype# => true


来源:https://stackoverflow.com/questions/5933569/what-is-the-easiest-way-to-test-for-class-membership-in-coffeescript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!