有没有办法在google apps脚本中检查againts内置类型? 我不知道如何访问内置类型的构造函数。所以我不能使用instaceof运算符。
例如个人资料(https://developers.google.com/apps-script/class_analytics_v3_schema_profile)
function getReportDataForProfile(profile) {
if (profile instanceof Profile) // Profile is undefined...
...
}
还有什么是令人困惑的:当我得到一个Profile的实例(在变量配置文件中)
profile.constructor // is undefined
答案 0 :(得分:6)
在观察Logger.log()
的输出后,很明显,对于大多数内置的Google Apps对象,toString()
方法的输出是类名:
var sheet = SpreadsheetApp.getActiveSheet()
if (typeof sheet == 'object')
{
Logger.log( String(sheet) ) // 'Sheet'
Logger.log( ''+sheet ) // 'Sheet'
Logger.log( sheet.toString() ) // 'Sheet'
Logger.log( sheet ) // 'Sheet' (the Logger object automatically calls toString() for objects)
}
所以上面的任何一个都可以用来测试对象的类型(最后一个显然只适用于Logger
的例子除外)
答案 1 :(得分:0)
似乎这不一定是一个必要的清洁解决方案,但它仍将是功能性的。
如果是Profile对象,则profile.getKind()
将返回analytics#profile
。但是,如果没有为该对象定义.getKind()
方法,则会抛出错误。所以看起来你必须做2次检查。
if (typeof profile.getKind != "function") {
if (profile.getKind() == "analytics#profile") {
//profile is a Profile!
} else {
//profile is some other kind of object
//use getKind() to find out what it is!
}
} else {
//profile doesn't have a getKind method
//need a different way of determining what it is
}
答案 2 :(得分:0)
在某些情况下,“ in”可用于通过对象的属性来验证对象:
function CheckType( fileOrFolder ) {
if ( "getName" in fileOrFolder )
if ( "getFiles" in fileOrFolder ) return "folder" ;
else if ( "getBlob" in fileOrFolder) return "file" ;
return "neither file nor folder" ;
}
function ShowType( Obj ) {
let Type = CheckType( Obj ) ;
console.log( "%s is a %s", "getName" in Obj ? Obj.getName() : Obj.toString(), Type ) ;
}
ShowType( DriveApp.getFiles().next() ) ;
ShowType( DriveApp.getFolders().next() ) ;
ShowType( DriveApp ) ;