Javascript对象变量在object方法中不可用

时间:2014-09-07 15:10:39

标签: javascript javascript-objects

我正在尝试javascript对象。有趣的是,当我尝试在方法中使用变量时,它告诉我要么是未定义的,要么是找不到该方法。

var oPdf = {
  hFolderHandle: DocsList.getFolderById('0B1rbQnVtcj5CNWNmekFWMG9DZzA'),
  hTempHtmlHandle: "",
  hPdfHandle: "",

  mToastFeedback: function () {
    SpreadsheetApp.getActiveSpreadsheet().toast('Finished');
  }
};
oPdf.hTempHtmlHandle = oPdf.hFolderHandle.createFile('test.html', oInvoice.sInvoiceBody, 'text/html');
oPdf.hPdfHandle = oPdf.hFolderHandle.createFile(oPdf.hTempHtmlHandle.getAs('application/pdf')).rename('test.pdf');
DocsList.getFileById(oPdf.hTempHtmlHandle.getId()).setTrashed(true);

例如,如果我将行oPdf.hTempHtmlHandle = oPdf.hFolderHandle.createFile('test.html', oInvoice.sInvoiceBody, 'text/html');移动到方法中 在oPdf中,如下:

 mTestMethod:function () {
      oPdf.hTempHtmlHandle = oPdf.hFolderHandle.createFile('test.html', oInvoice.sInvoiceBody, 'text/html');
 },

Google Apps脚本告诉我hFolderHandle不知道createFile方法。

有什么想法吗?


确定这个有效,在上面的例子中就好了,但这里没有,我不知道,为什么。

var oSpreadSheetApp = {
    hSpreadSheet: SpreadsheetApp.getActiveSpreadsheet(), //Retrieving the handle to the currently open spread-sheet
    hInvoiceSheet: this.hSpreadSheet.getSheetByName('Rechnungen')
};

1 个答案:

答案 0 :(得分:0)

由于您的方法mTestMethodoPdf对象的一部分,因此您可以通过调用this修改:或{来)像任何属性或方法一样访问它{1}})这是对象的“指针”。

评论后编辑:

问题在于oPdfoPdf.hFolderHandle不知道任何名为this.hFolderHandle的方法。


createFile()

很多 Felix Kling 指向!


问题更新后更新

这段代码:

mTestMethod:function () {
     // calling with the object itself  
     oPdf.hTempHtmlHandle = oPdf.hFolderHandle.createFile('test.html', oInvoice.sInvoiceBody, 'text/html');
     // or calling by 'this' is the same
      this.hTempHtmlHandle = oPdf.hFolderHandle.createFile('test.html', oInvoice.sInvoiceBody, 'text/html');
 },

应该是

var oSpreadSheetApp = {
    hSpreadSheet: SpreadsheetApp.getActiveSpreadsheet(), //Retrieving the handle to the currently open spread-sheet
    hInvoiceSheet: this.hSpreadSheet.getSheetByName('Rechnungen')
};

因为var oSpreadSheetApp = { hSpreadSheet: SpreadsheetApp.getActiveSpreadsheet(), //Retrieving the handle to the currently open spread-sheet hInvoiceSheet: SpreadsheetApp.getSheetByName('Rechnungen') }; 显然是 对象SpreadsheetApp的一部分。