首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在JavaScript中同时定义和未定义的对象(在FireFox扩展中)

在JavaScript中同时定义和未定义的对象(在FireFox扩展中)
EN

Stack Overflow用户
提问于 2010-02-23 07:03:12
回答 2查看 643关注 0票数 16

我正在查找FireFox扩展中的bug。我终于亲眼看到了(我以前只收到过报告),我不明白我所看到的是怎么可能的。

来自error Console中我的扩展的一条错误消息是"gBrowser is not defined“。这本身就足够令人惊讶了,因为覆盖是在browser.xul和navigator.xul之上的,我希望gBrowser可以从这两个平台上获得。更糟糕的是它发生的实际位置:nextplease.js的101行。也就是说,在仅从onContentLoaded调用的函数isTopLevelDocument内,该函数仅在此处从onLoad调用:

代码语言:javascript
复制
gBrowser.addEventListener(this.loadType, function (event) {
    nextplease.loadListener.onContentLoaded(event);
},
true);

所以gBrowser是在onLoad中定义的,但不知何故在isTopLevelDocument中没有定义。

当我尝试实际使用这个扩展时,我得到了另一个错误:“未定义下一个”。有趣的是,它发生在853和857行。也就是说,在函数内部

代码语言:javascript
复制
nextplease.getNextLink = function () {
    nextplease.getLink(window.content, nextplease.NextPhrasesMap, nextplease.NextImagesMap, nextplease.isNextRegExp, nextplease.NEXT_SEARCH_TYPE);
}

nextplease.getPrevLink = function () {
    nextplease.getLink(window.content, nextplease.PrevPhrasesMap, nextplease.PrevImagesMap, nextplease.isPrevRegExp, nextplease.PREV_SEARCH_TYPE);
}

因此,nextplease以某种方式被定义为足以调用这些函数,但没有在它们内部定义。

最后,在Execute JS中执行typeof(nextplease)返回"object“。gBrowser也是如此。

这怎么会发生呢?有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2010-02-26 01:47:33

对于第二种情况:

代码语言:javascript
复制
nextplease.getNextLink = function () {
    nextplease.getLink(window.content, nextplease.NextPhrasesMap, nextplease.NextImagesMap, nextplease.isNextRegExp, nextplease.NEXT_SEARCH_TYPE);
}

nextplease.getPrevLink = function () {
    nextplease.getLink(window.content, nextplease.PrevPhrasesMap, nextplease.PrevImagesMap, nextplease.isPrevRegExp, nextplease.PREV_SEARCH_TYPE);
}

我会尝试这样做:

代码语言:javascript
复制
nextplease.getNextLink = function () {
    this.getLink(window.content, this.NextPhrasesMap, this.NextImagesMap, this.isNextRegExp, this.NEXT_SEARCH_TYPE);
}

nextplease.getPrevLink = function () {
    this.getLink(window.content, this.PrevPhrasesMap, this.PrevImagesMap, this.isPrevRegExp, this.PREV_SEARCH_TYPE);
}
票数 2
EN

Stack Overflow用户

发布于 2010-06-02 02:29:09

我不确定发生了什么(代码在哪个上下文中运行,因此它看不到gbrowser和其他全局变量),但是gbrowser未定义的一个简单的解决方法是获取对主窗口的引用并从那里访问它:

代码语言:javascript
复制
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                     .getInterface(Components.interfaces.nsIWebNavigation)
                     .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                     .rootTreeItem
                     .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                     .getInterface(Components.interfaces.nsIDOMWindow);

mainWindow.gbrowser.addEventListener( ... )

这应该独立于代码运行的上下文,因为您不会依赖于全局变量。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2314961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档