为什么无法从chrome.downloads.onChanged内部调用函数?

时间:2018-12-10 01:51:57

标签: javascript this listener typeerror

我第一次在chrome中创建扩展程序(我不是网络用户,也不是javascript开发人员)。我要添加一个从未使用过的javascript较旧版本的代码库(一旦我在具有该代码库的计算机上,我会标记它是哪个版本,但我不记得了)。

我有一个叫做DownloadManager的类,在其中我调用chrome.downloads.onChanged,在其中我调用了该类内部的另一个函数,但是它无法识别该类(我认为这就是问题所在)。

// 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。我确定所接受的参数与上面声明的函数的类型相同。

当我回到那个环境时,我将添加更多数据。

1 个答案:

答案 0 :(得分:1)

chrome.downloads.onChanged的事件处理程序中,this关键字现在与this内部的DownloadManager具有不同的上下文。可能有道理,因为您在downloadManager中定义了事件处理程序,因此可以共享该变量,但这恰好是“定义代码的位置与调用代码的位置”的巧合。

在主作用域中将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);
        }
    }
}