【问题标题】:Get class type in CoffeeScript在 CoffeeScript 中获取类类型
【发布时间】:2012-03-20 11:36:37
【问题描述】:

实例化后如何找到对象的该类?

class Cat
  constructor: (@name) ->

class Dog
  constructor: (@name) ->

cat = new Cat "Kitty"
dog = new Dog "Doggy"

if (cat == Cat)  <- I want to do something like this

【问题讨论】:

    标签: coffeescript


    【解决方案1】:

    执行此操作的方法是使用以下任一方法检查对象的类型

    instanceof
    

    typeof
    

    if (obj instanceof Awesomeness){
    //doSomethingCrazy();
    }
    

    就像在 JavaScript 中一样,Coffee Script 不提供对这些函数的任何抽象

    【讨论】:

    • 有没有办法通过猜测和检查来获取对象的名称?
    • @Alexis 我认为 typeof 是你想要的。
    【解决方案2】:

    只需将== 更改为instanceof

    if(cat instanceof Cat)
    

    【讨论】:

    【解决方案3】:

    AFAIU,一般的解决方案是使用@constructor - 当您不知道或不想指定类名时很有用。

    甚至有a discussion 将@@ 设为它的快捷方式。

    【讨论】:

      【解决方案4】:

      如果您想知道特定对象的类型名称(这是我在发现这个问题时正在寻找的),您可以使用语法{object}.constructor.name

      例如

      class Cat
          constructor: (@name) ->
      
        class Dog
          constructor: (@name) ->
      
        cat = new Cat()
        dog = new Dog()
      
        console.log cat.constructor.name
        console.log dog.constructor.name
      

      哪个会输出

      Cat
      Dog
      

      【讨论】:

        猜你喜欢
        • 2021-10-15
        • 2012-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-25
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        相关资源
        最近更新 更多