【问题标题】:Google Apps Script Hoisting and ReferenceErrorGoogle Apps 脚本提升和引用错误
【发布时间】:2021-07-14 14:11:43
【问题描述】:

这几周我一直在尝试寻找答案,但无法完全做到这一点,所以我决定问一下。

我有时会收到此错误:

ReferenceError: 未定义

...而我确信它是。问题是对象位于不同的文件中,所以如果我从该文件(甚至可能是第三个文件)调用对象,代码确实可以工作。

我相信这一定与hoisting 的工作方式有关,这意味着我试图在声明对象之前调用它。

但是当你有不同的文件时它是如何工作的呢?

这是一个例子:

如果我在一个文件中有以下代码并且我运行getID(),它可以工作:

const SomeAPI = (function () {
  const _auth = new WeakMap();
  const _url = new WeakMap();

  class SomeAPI {
    constructor(url, user = DEFAULT_USER, pwd = DEFAULT_PWD) {
      _url.set(this, url);
      _auth.set(this, Utilities.base64Encode(`${user}:${pwd}`));
    }

    async fetch() {
      const headers = {
        Authorization: `Basic ${_auth.get(this)}`,
      };

      const options = {
        headers,
      };

      const response = await UrlFetchApp.fetch(_url.get(this), options);
      const data = JSON.parse(response);
      return data;
    }
  }

  return SomeAPI;
})();

const LIST_DATA = (async () => await getListData())();

async function getListData() {
  const response = await new SomeAPI(ALL_SETTINGS['List API URL']).fetch();
  return Array.isArray(response) ? response[0] : response;
}


const getID = async () => {
  const listData = await LIST_DATA;
  const listId = listData.list_id;
  const id = {
    sheetId: SpreadsheetApp.getActive().getId(),
    listId
  };
  console.log(id);
  return id;
};

但是,如果我将 LIST_DATAgetListData()getID() 移动到不同的文件,我会得到:

ReferenceError: SomeAPI 未定义

整个项目由 17 个不同的文件组成。

非常感谢所有帮助!

【问题讨论】:

  • 尝试将 someAPI 所在的文件定位在调用的文件上方
  • @Cooper 你的意思是按字母顺序?
  • 在新编辑器中您可以移动文件。
  • 太棒了,你是一个活生生的救星,谢谢!随意写下你的答案,我很乐意接受!
  • BTW @Cooper 事实证明,当您重新加载项目时,文件顺序不会保留,所以我最终将 Code.gs 重命名为 zCode.gs,但您让我走上了正确的轨道,非常感谢

标签: javascript google-apps-script hoisting


【解决方案1】:

根据@Cooper 对您的问题的评论,向上移动文件是可行的。我创建的课程也有同样的问题。我将带有类的文件移到顶部,它解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    相关资源
    最近更新 更多