javascript - typescript - 我如何获取对象的类实例?
我有一个 classA 类的对象,它继承自 classB 类
我的问题是:我怎么知道我的对象是否继承自 classB
我尝试了:Object instanceof classB
但是它不起作用!
当我在任何 TS 文件中添加 instanceof 时,我遇到
0x800a138f - Microsoft JScript 运行时错误:无法获取属性 'prototype' 的值:对象为 null 或未定义
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype; //exception occurs in this line
d.prototype = new __();
};
答案#1
这个错误的一个原因是,如果你继承的类在文件中出现在派生类之后。
这个(曲解一下Ryan的答案):
class B extends A {
}
class A {
}
var x = new B();
console.log(x instanceof A); // Error
... 正是导致您在 Playground 中描述的错误。
我认为在 CodePlex 上已经有一个关于这个的工作项了,但时间晚了,我还没有检查……
答案#2
这通常是可行的:
class A {
}
class B extends A {
}
var x = new B();
console.log(x instanceof A); // true
