如何判断实例的 class
How to tell the class of an instance
有没有办法告诉 class 一个对象在 Typescript 中是什么实例?我的意思不仅仅是 'Object'.
如果你有这个:
const x : MyClass = new MyClass();
console.log(typeof(x));
你会得到:
'Object'
那么如果你这样做了:
console.log(x instanceof MyClass);
你会得到:
Uncaught ReferenceError: MyClass is not defined
如何打印出来'MyClass'?
您可以使用 x.constructor.name
.
函数的 .constructor
property of an object holds a reference to the constructor function that created the instance (the class function) and the .name
属性 保留其名称。
这是JavaScript,不涉及TypeScript。 TypeScript 类型在这里没有帮助,它们在编译为 JavaScript 代码时消失。
有没有办法告诉 class 一个对象在 Typescript 中是什么实例?我的意思不仅仅是 'Object'.
如果你有这个:
const x : MyClass = new MyClass();
console.log(typeof(x));
你会得到:
'Object'
那么如果你这样做了:
console.log(x instanceof MyClass);
你会得到:
Uncaught ReferenceError: MyClass is not defined
如何打印出来'MyClass'?
您可以使用 x.constructor.name
.
函数的 .constructor
property of an object holds a reference to the constructor function that created the instance (the class function) and the .name
属性 保留其名称。
这是JavaScript,不涉及TypeScript。 TypeScript 类型在这里没有帮助,它们在编译为 JavaScript 代码时消失。