【问题标题】:Type checking on google apps script platform谷歌应用脚​​本平台上的类型检查
【发布时间】:2013-03-10 17:34:34
【问题描述】:

有没有办法检查谷歌应用脚​​本中的内置类型? 我不知道如何访问内置类型的构造函数。所以我不能使用 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

【问题讨论】:

  • 为什么需要 Profile 构造函数?你想做什么?
  • 我不确定是否需要构造函数。我想测试配置文件(函数参数)是否是配置文件的实例。当然这只是例子。我想为任何对象执行此操作。虽然“鸭子打字”总是可能的,但我希望有一些简单的解决方案。

标签: google-apps-script


【解决方案1】:

观察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的例子)

【讨论】:

    【解决方案2】:

    这似乎不一定是一个干净的解决方案,但它仍然可以正常工作。

    如果是 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
    }
    

    【讨论】:

    • 这实际上是一个不错的解决方案!不幸的是,getKind 方法并没有通过谷歌 API 始终如一地使用。似乎 getKind 仅适用于“Google API 服务”。但不适用于电子表格或 Gmail 等“默认服务”。
    • 这是我发现准确识别 Profile 对象的唯一方法。我知道它不会识别任何其他对象。
    【解决方案3】:

    在某些情况下,“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 ) ;
    

    【讨论】:

      猜你喜欢
      • 2017-07-21
      • 1970-01-01
      • 2013-02-20
      • 2021-03-05
      • 1970-01-01
      • 2012-07-24
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多