Typescript 比较具有相同父类的派生类的实例
我有两个类扩展同一父类,如下所示:Typescript 比较具有相同父类的派生类的实例,typescript,inheritance,comparison,derived-class,typeof,Typescript,Inheritance,Comparison,Derived Class,Typeof,我有两个类扩展同一父类,如下所示: class ParentClass{ ... } class Son extends ParentClass{ ... } class Daughter extends ParentClass{ ... } 我希望有类似于此伪代码的代码: a.getClass() === b.getClass(); 仅当两个变量都是同一派生类的实例时(例如,在本例中为Son或children) 我希望有类似的代码: typeof a === typeof b 仅当两个
class ParentClass{ ... }
class Son extends ParentClass{ ... }
class Daughter extends ParentClass{ ... }
我希望有类似于此伪代码的代码:
a.getClass() === b.getClass();
仅当两个变量都是同一派生类的实例时(例如,在本例中为Son
或children
)
我希望有类似的代码:
typeof a === typeof b
仅当两个变量都是同一派生类的实例时(例如,在本例中为Son
或children
)才返回true
不,如果a
和b
是任何类型的对象,包括与父类
完全无关的对象,则返回true,因为类型的
对于任何对象都将是“对象”
,当然,“对象”==“对象”
是true
instanceof
如果左侧操作数的原型链包含右侧操作数引用的对象,则返回true
。prototype属性,因此instanceof
将按照您的描述工作:
a instanceof ParentClass === b instanceof ParentClass
实例:
class父类{}
类Son扩展父类{}
类子类扩展父类{}
常数a=新儿子();
常数b=新女儿();
console.log(父类的a instanceof ParentClass==b instanceof ParentClass);//真的
常数c=新的子();
常数d=新映射();//不是父类的子类
console.log(c instanceof ParentClass==d instanceof ParentClass);//false
如果要确定两个任意对象是否共享同一个祖先,则需要递归地比较这两个对象的原型
我编写了一个函数,它可以接受两个未知类型的东西,并将告诉您它们是否共享一个共同的祖先:
函数sharesParent(同级:未知,可能同级:未知):布尔值{
if(同级!==null&&possiblesiling!==null){
const objectPrototype=Object.getPrototypeOf({});
const functionPrototype=Object.getPrototypeOf(函数);
让currentSiblingPrototype=Object.getPrototypeOf(同级);
while(currentSiblingPrototype!==objectPrototype&¤tSiblingPrototype!==functionPrototype){
让currentPossibleSiblingPrototype=Object.getPrototypeOf(possibleSibling);
while(currentPossibleSiblingPrototype!==objectPrototype&¤tPossibleSiblingPrototype!==functionPrototype){
if(currentPossibleSiblingPrototype==currentSiblingPrototype){
console.log(currentPossiblingPrototype);
返回true;
}
currentPossibleSiblingPrototype=Object.getPrototypeOf(currentPossibleSiblingPrototype);
}
currentSiblingPrototype=Object.getPrototypeOf(currentSiblingPrototype);
}
}
返回false;
}
类岩石{}
花岗岩类延伸岩石{}
石灰岩类延伸岩{}
类动物{}
类{}
马类动物{}
类小马{}
console.log(
sharesParent(新小马、新花岗岩)/*假*/,,
sharesParent(新熊猫、新小马)/*正确*/,,
sharesParent(新小马、新马)/*正确*/,,
sharesParent(“字符串”、“第二字符串”)/*true*/,,
sharesParent(“字符串”,42)/*false*/,,
sharesParent(映射,集)/*false*/,,
);
如果你知道你在寻找什么样的共享祖先,最好使用T.J.Crowder建议的instanceof
。你是说instanceof
?因为typeof
不提供类,它只提供基本类型。如“字符串”
、“数字”
、“对象”
、“函数”
等。谢谢。我想知道两个变量是否是同一个派生类的实例。我原来的问题措辞很混乱,所以我编辑了它。@Hade0011-啊!我在答案中添加了一些内容,以向您展示如何做到这一点。谢谢。太好了@Hade0011-我刚刚意识到答案没有涉及子类,所以我已经澄清了这一部分。您可能需要一个b.constructor的实例
或a.constructor==b.constructor
,具体取决于您想做什么。@AlpeinWorldCup:谢谢。我不想知道两个变量的类是否共享同一个祖先。我想知道它们是否是完全相同类的实例。比较foo
的两个实例应返回true
。比较foo
和bar
应返回false
,即使foo
和bar
都扩展了相同的类。@Hade0011如果是这种情况,那么它正是sharesParent
所做的。你试过了吗?它起作用了吗?