簡體   English   中英

我可以向 Google Apps 腳本類添加自定義方法嗎?

[英]Can I add custom methods to Google Apps Script classes?

我想在 Google Apps Script 類(例如SpreadsheetSheetDriveApp )上調用自定義方法。 https://stackoverflow.com/a/6117889中,使用最小的原型設計解決方案將方法添加到 Javascript Date() ZA2F2ED4F8EBC2CBB4C21A29DC40AB61 以獲取周數。 是否可以將相同的策略應用於 Google Apps 腳本類?

例如,我想為電子表格 class 創建一個自定義方法,該方法允許將電子表格移動到我的谷歌驅動器中的特定文件夾(給定該文件夾的 ID)。 這是我嘗試過的:

Spreadsheet.prototype.moveToFolder = function(folderID) {
  const file = DriveApp.getFileById(this.getId());
  const destination = DriveApp.getFolderById(folderID);
  file.moveTo(destination);
}

但是,我收到錯誤消息“ReferenceError:電子表格未定義”。 還有其他方法可以實現我想要的嗎?

可以添加自定義方法。 但是Spreadsheet class 不能直接訪問。 因此,首先需要使用任何可用方法獲取電子表格 class 的實例:

const Spreadsheet = SpreadsheetApp.getActive();

然后在Spreadsheet實例上使用Object.getPrototypeOf()來獲取它的原型。

Object.getPrototypeOf(Spreadsheet).myMethod = function (){
  console.info("myMethod was called!")
  return true;
}

然后原型上定義的任何屬性將通過所有電子表格實例傳播。

更新:

Object.getPrototypeOf(Spreadsheet)返回的原型 object 是Object 這也可以通過記錄Spreadsheet.constructor.name來確認。 這意味着沒有用於創建電子表格實例的特殊電子表格原型或構造函數 因此,盡管您可以添加自定義方法,但它們已添加到所有對象中,例如RangeDriveApp以及使用var obj = {}Object.create("Any object except null")

鑒於電子表格沒有獨特的原型,但實際上使用了Object的原型,正如TheMaster指出的,您可以簡單地將您的方法添加到Object原型中。

Object.prototype.moveToFolder = function(folderID) {
  const file = DriveApp.getFileById(this.getId());
  const destination = DriveApp.getFolderById(folderID);
  file.moveTo(destination);
}

由於此方法將適用於所有對象,因此您應該問自己是否真的值得這樣做。 請參閱“ 為什么擴展本機對象是一種不好的做法?

您可以創建一個新的 class,而不是修改本機 object,它“繼承”本機方法,同時還使您能夠覆蓋和添加新方法。

function main() {
  const ss = new Spreadsheet(SpreadsheetApp.getActive());
  console.log(ss._native.getName()); // MySpreadsheet
  console.log(ss.getName()); // The name is MySpreadsheet
  
  ss.moveToFolder(FOLDER_ID);
}

class Spreadsheet {
  constructor(native) {
    this._native = native;
    
    // Copy native's methods to this
    Object.getOwnPropertyNames(this._native).forEach(property => {
      this[property] = this._native[property];
    });
    
    // Override native methods
    Object.defineProperties(this, {
      'getName': {
        value: function() {
          return `The name is ${this._native.getName()}`;
        }
      }
    });
  }
  
  moveToFolder(folderId) {
    const file = DriveApp.getFileById(this.getId());
    const destination = DriveApp.getFolderById(folderId);
    file.moveTo(destination);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM