一旦对象被实例化,我如何找到它的类呢?
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
发布于 2012-03-02 07:03:36
只需将==
更改为instanceof
if(cat instanceof Cat)
发布于 2014-12-15 19:30:22
如果您想知道特定对象的类型名称(这就是我发现这个问题时正在查找的内容),您可以使用语法{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
发布于 2012-03-02 06:58:55
执行此操作的方法是使用以下任一方法检查对象的类型
instanceof
或
typeof
即
if (obj instanceof Awesomeness){
//doSomethingCrazy();
}
就像在JavaScript中一样,Coffee Script不提供对这些函数的任何抽象
https://stackoverflow.com/questions/9525292
复制相似问题