2013-03-10 49 views
0

有沒有一種方法來檢查googlets應用程序腳本中的內置類型? 我不知道如何訪問內置類型的構造函數。所以我不能使用instaceof操作符。谷歌應用程序腳本平臺上的類型檢查

例如個人資料(https://developers.google.com/apps-script/class_analytics_v3_schema_profile

function getReportDataForProfile(profile) { 
if (profile instanceof Profile) // Profile is undefined... 
... 
} 

還什麼是痘痘困惑:當我拿到資料的一個實例(可變輪廓)

profile.constructor // is undefined 
+1

爲什麼您需要Profile構造函數?你想做什麼? – 2013-03-10 19:12:05

+0

我不確定我是否需要構造函數。我想測試配置文件(功能參數)是否屬於配置文件。 當然這只是一個例子。我想爲任何物體做這件事。 雖然「鴨子打字」總是有可能,但我希望有一些簡單的解決方案。 – vetvicka 2013-03-11 19:12:38

回答

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 
} 
+0

這實際上是很好的解決方案!不幸的是getKind方法並沒有一直使用谷歌API。似乎getKind僅適用於「Google API服務」。但不適用於電子表格或Gmail等「默認服務」。 – vetvicka 2013-03-11 21:30:46

+0

這是我發現準確識別配置文件對象的唯一方法。我知道它沒有識別任何其他物體。 – 2013-03-12 01:46:00

5

觀測Logger.log()輸出後,很顯然,對於大多數內置了谷歌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

相關問題