Javascript 我可以向Google Apps脚本类添加自定义方法吗?

Javascript 我可以向Google Apps脚本类添加自定义方法吗?,javascript,google-apps-script,prototype,Javascript,Google Apps Script,Prototype,我想在GoogleApps脚本类(如电子表格、工作表和DriveApp)上调用自定义方法。 在中,使用最小原型解决方案向Javascript Date()类添加一个方法以获取周数。是否有可能将相同的策略应用到Google应用程序脚本类 例如,我想为电子表格类创建一个自定义方法,该方法允许在给定文件夹ID的情况下,将电子表格移动到google drive中的特定文件夹。以下是我尝试过的: Spreadsheet.prototype.moveToFolder = function(folderID)

我想在GoogleApps脚本类(如电子表格、工作表和DriveApp)上调用自定义方法。 在中,使用最小原型解决方案向Javascript Date()类添加一个方法以获取周数。是否有可能将相同的策略应用到Google应用程序脚本类

例如,我想为电子表格类创建一个自定义方法,该方法允许在给定文件夹ID的情况下,将电子表格移动到google drive中的特定文件夹。以下是我尝试过的:

Spreadsheet.prototype.moveToFolder = function(folderID) {
  const file = DriveApp.getFileById(this.getId());
  const destination = DriveApp.getFolderById(folderID);
  file.moveTo(destination);
}
但是,我收到错误消息“ReferenceError:电子表格未定义”。
是否有其他方法可以实现我的目标?

可以添加自定义方法。但是,
电子表格
类不能直接访问。因此,首先需要使用任何可用方法获取电子表格类的实例:

const Spreadsheet = SpreadsheetApp.getActive();
然后使用
电子表格
实例获取其原型

Object.getPrototypeOf(Spreadsheet).myMethod = function (){
  console.info("myMethod was called!")
  return true;
}
Object.prototype.moveToFolder = function(folderID) {
  const file = DriveApp.getFileById(this.getId());
  const destination = DriveApp.getFolderById(folderID);
  file.moveTo(destination);
}
在原型上定义的任何属性都将通过所有电子表格实例传播

更新:
object.getPrototypeOf(电子表格)
返回的原型对象是
object
。这也可以通过记录
电子表格.constructor.name
来确认这意味着没有用于创建电子表格实例的特殊电子表格原型或构造函数。因此,尽管您可以添加自定义方法,但它们被添加到所有对象中,例如,
Range
DriveApp
,以及使用
var obj={}
object.create创建的任何对象。create(“除null以外的任何对象”)

,因为电子表格没有唯一的原型,但实际上使用的是
对象的原型,与之前一样,您可以简单地将您的方法添加到原型中

Object.getPrototypeOf(Spreadsheet).myMethod = function (){
  console.info("myMethod was called!")
  return true;
}
Object.prototype.moveToFolder = function(folderID) {
  const file = DriveApp.getFileById(this.getId());
  const destination = DriveApp.getFolderById(folderID);
  file.moveTo(destination);
}
由于此方法将应用于所有对象,因此您应该问问自己是否真的值得这样做。见“

不必修改本机对象,您可以创建一个“继承”本机方法的新类,同时还可以重写和添加新方法

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);
  }
}