Answers:
4.19.4 instanceof运算符
在
instanceof
操作者需要的左操作数是类型的任何,对象类型,或类型参数类型和右操作数是任何类型或“功能”接口类型的子类型的。结果始终是布尔基元类型。
所以你可以使用
mySprite instanceof Sprite;
请注意,该运算符也位于ActionScript中,但现在不应再在其中使用:
is运算符是ActionScript 3.0的新增功能,它使您能够测试变量或表达式是否是给定数据类型的成员。在早期版本的ActionScript中,instanceof运算符提供了此功能,但在ActionScript 3.0中,不应将instanceof运算符用于测试数据类型成员身份。手动类型检查应使用is运算符,而不是instanceof运算符,因为表达式x instanceof y只是检查x的原型链是否存在y(并且在ActionScript 3.0中,原型链无法提供的完整图片继承层次结构)。
TypeScript instanceof
存在相同的问题。由于这是一种仍在发展中的语言,因此我建议您陈述有关此功能的建议。
也可以看看:
TypeScript具有一种在运行时验证变量类型的方法。您可以添加一个返回类型谓词的验证函数。因此,您可以在if语句内调用此函数,并确保该块内的所有代码都可以安全地用作您认为的类型。
来自TypeScript文档的示例:
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
}
详情请参见:https: //www.typescriptlang.org/docs/handbook/advanced-types.html
isFish
本身所创建的断言,它的身体没有成为一个班轮谓语。这样做的好处是,编译器在编译时理解适当的可能函数,但是内部的代码isFish
在运行时执行。您甚至可以让防护包含一条instanceof
语句,例如return pet instanceof Fish
(假设它是一个类,而不是一个接口),但这是不必要的,因为编译器可以instanceof
直接理解。
您可以instanceof
为此使用运算符。从MDN:
instanceof运算符测试构造函数的prototype属性是否出现在对象的原型链中的任何位置。
如果您不知道什么是原型和原型链,我强烈建议您进行查找。这也是一个JS(TS在这方面的工作原理类似)示例,它可以阐明概念:
class Animal {
name;
constructor(name) {
this.name = name;
}
}
const animal = new Animal('fluffy');
// true because Animal in on the prototype chain of animal
console.log(animal instanceof Animal); // true
// Proof that Animal is on the prototype chain
console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true
// true because Object in on the prototype chain of animal
console.log(animal instanceof Object);
// Proof that Object is on the prototype chain
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true
console.log(animal instanceof Function); // false, Function not on prototype chain
本示例中的原型链为:
动物>动物原型>对象原型
Std.is(pet, Fish)
,它在类型的作品,接口等