我是第一次在chrome中创建扩展(我不是网络或javascript开发人员) . 我正在添加一个代码库,这个代码库是我从未使用过的旧版本的javascript(一旦我在拥有该代码库的计算机上,我会标记它是哪个版本,但我记不住了) .
我有一个名为DownloadManager的类,在其中我调用了chrome.downloads.onChanged,在其中,我调用了类中的另一个函数,但它可以't recognize the class (I think that'这个问题) .
// 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>
.
我'm assuming it'是一个范围问题,并且 this.
在那里没有't mean anything there, and it can'访问 doAThing
. 我确定所采用的参数与上面声明的函数的类型相同 .
当我回到那个环境时,我会添加更多数据 .
1 回答
在
chrome.downloads.onChanged
的事件处理程序中,this
关键字现在与DownloadManager
内的this
具有不同的上下文 . 可能有意义的是,因为您在downloadManager
中定义了可以共享变量的事件处理程序,但这恰好是"where the code was defined vs where the code is invoked from"的巧合 .您可能可以将
this
分配给主范围中的变量: