为什么我不能从 chrome.downloads.onChanged 内部调用函数?

Why can't I call function from inside chrome.downloads.onChanged?

我是第一次在 chrome 中创建扩展(我不是 Web 或 javascript 开发人员)。我正在添加一个我从未使用过的旧版本 javascript 中的代码库(一旦我在具有该代码库的计算机上,我将标记它是哪个版本,但我可以'不记得了)。

我有一个名为 DownloadManager 的 class,我在其中调用 chrome.downloads.onChanged,在其中,我在 class 中调用另一个函数,但它不能'无法识别 class(我认为这就是问题所在)。

// Class named DownloadManager
function DownloadManager(someData) {

    this._myData = someData;

    // function that does a thing, and tests run successfully
    this.doAThing = function(someData) {
        // Code in here that we assume works, and there's no issues.
    }

    if(chrome.downloads) {
        chrome.downloads.onChanged.addListener(function(delta) {
            // Error here
            this.doAThing(delta.data);
        }
    }
}

我遇到的错误在 this.doAThing(this._myData); 行。错误是 Error in event handler for downloads.onChanged: TypeError: Cannot read property 'doAThing' of null at <URL>.

我假设这是一个范围问题,this. 在那里没有任何意义,它无法在那里访问 doAThing。我确定传入的参数与上面声明的函数的类型相同。

回到那个环境后我会添加更多数据。

chrome.downloads.onChanged 的事件处理程序中,this 关键字现在与 DownloadManager 中的 this 具有不同的上下文。这可能是有道理的,因为您在 downloadManager 中定义了事件处理程序,您可以共享变量,但这恰好是 "where the code was defined vs where the code is invoked from" 的巧合。

您可以将 this 分配给主作用域中的变量:

function DownloadManager(someData) {
    this.doAThing = function(someData) {
        // Code in here that we assume works, and there's no issues.
    }

    window.myScope = this;

    if(chrome.downloads) {
        chrome.downloads.onChanged.addListener(function(delta) {
            // Error here
            window.myScope.doAThing(delta.data);
        }
    }
}