确定对象的确切类型/类别



如果我有一个变量,我想知道对象的确切类型,我该怎么做?

// this prints "object"
// any way to know what kind of object
// like whether a GlideRecord or Reference Field or array or json?
gs.log(typeof myVariable);

如果GlideRecord等是类或构造函数,则可以使用constructor属性。

class GlideRecord {}
// or legacy constructor function - 
// function GlideRecord() {}
const instance = new GlideRecord()
const { constructor } = instance
console.log(constructor)                 // GlideRecord
console.log(constructor.name)            // "GlideRecord"
console.log(constructor === GlideRecord) // true

请注意,如果它们只是用工厂函数创建的普通旧JS对象,则将不起作用-在这种情况下,constructor将只是Object:

const createGlideRecord = () => {
return { /* ... */ }
}
const instance = createGlideRecord()
const { constructor } = instance
console.log(constructor)                       // Object
console.log(constructor.name)                  // "Object"
console.log(constructor === createGlideRecord) // false

最新更新