如何测试类实例是否是它扩展的类的实例?

时间:2015-05-05 15:17:57

标签: coffeescript

class A
class B extends A

b = new B
b instanceof B # true
b instanceof A # false

我如何检查b是"还是" A的实例(因为B扩展了A

1 个答案:

答案 0 :(得分:2)

class A
class B extends A

b = new B
console.log "b is an instance of extended class " if b instanceof B # b is an instance of extended class 
console.log "b is an instance of extended class A because B extends a " if b instanceof A # b is an instance of extended class A because B extends a

您可以简单地使用:

if b instanceof B && b instanceof A  #B is instance of A and B classes
  console.log "B is instance of A and B classes" 

以下是代码片段: http://repl.it/meN/1