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

后端 未结 2 596
情歌与酒
情歌与酒 2021-02-02 13:21

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

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-02 14:07

    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'
    

提交回复
热议问题