在ActionScript中,可以在运行时使用is操作符检查类型:
var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite); // true
trace(mySprite is DisplayObject);// true
trace(mySprite is IEventDispatcher); // true
是否有可能检测一个变量(扩展或)是TypeScript的某个类或接口?
我在语言规范里找不到任何关于它的信息。在处理类/接口时,它应该存在。
4.19.4操作符的实例
instanceof操作符要求左操作数为Any类型,对象类型或类型形参类型,右操作数为Any类型或'Function'接口类型的子类型。结果总是布尔基元类型。
所以你可以用
mySprite instanceof Sprite;
注意,这个操作符也在ActionScript中,但不应该再使用了:
The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or expression is a member of a given data type. In previous versions of ActionScript, the instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof operator should not be used to test for data type membership. The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).
TypeScript的instanceof也有同样的问题。由于这是一门仍处于发展阶段的语言,我建议你提出这样一项建议。
参见:
MDN:运算符
您可以为此使用instanceof操作符。中数:
的原型属性是否为
构造函数出现在对象的原型链中的任何地方。
如果你不知道原型和原型链是什么,我强烈建议你去查一下。这里还有一个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
本例中的原型链为:
动物。Object.prototype