我有一个奇怪的问题,其中instanceof似乎无法在TypeScript中为派生类正常工作。我的课程结构如下:
interface Serializing
{
serialize(): string
}
class Storage implements Serializing
{
// constructor, methods, serialize, ...
}
class StorageContainer
{
// constructor, methods, various methods that act on storage_, ...
protected storage_: Storage;
}
class Derived extends StorageContainer
{
constructor()
{
super();
let test1 = this instanceof Derived; // succeeds
let test2 = this instanceof StorageContainer; // succeeds
}
// ... constructor, methods, ...
}
然后我使用这些类运行此方法:
testInstanceofOnDerivedClasses()
{
let derived = new Derived();
let test1 = derived instanceof Derived; // succeeds
let test2 = derived instanceof StorageContainer; // fails?
}
我当然希望test2是真的(因为类Derived显然是从类StorageContainer派生的),但由于某种原因它返回false ...
我还使用其他更简单的派生类进行了测试,并且instanceof确实按预期工作。只有在这种特殊情况下,我才会这样做。
同样值得注意的是:当我在Derived的构造函数中进行2次测试时,他们都成功了......
所以,我的问题是:
谢谢!