几个选项:
使用Function#bind:
我相信在 Firefox 扩展中,您应该拥有大部分(如果不是全部)ES5 功能,这意味着您可以使用Function#bind 来确保调用您的事件处理程序并将this 设置为您的实例。例如:
if (gBrowser) {
gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad.bind(this), false);
}
在对onPageLoad 的调用中,this 将引用您的实例。您将无法访问普通的 this Firefox 提供的事件处理程序(选项卡或其他)。
bind 选项的完整示例:
var myExtension = {
init: function() {
// The event can be DOMContentLoaded, pageshow, pagehide, <b style="color:black;background-color:#99ff99">load</b> or unload.
if(gBrowser) {
gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad.bind(this), false);
}
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
var win = doc.defaultView; // win is the window for the doc
alert("<b style="color:black;background-color:#a0ffff">page</b> is loaded \n" +doc.location.href);
// This now works
Firefox.Console.log(this.userName);
// ...but you don't have access to the `this` that the browser gave
// the event handler (the tab or whatever)
},
anotherMethod: function (){
this.userName = 'UserName';
}
}
window.addEventListener("<b style="color:black;background-color:#99ff99">load</b>", function() { myExtension.init(); }, false);
使用闭包:
如果我对 Firefox 扩展中的 ES5 有误,或者如果您想访问事件处理程序通常会收到的 this,您可以轻松地使用闭包来做同样的事情:
var self = this;
if (gBrowser) {
gBrowser.addEventListener("DOMContentLoaded", function(event) {
// Here, `self` refers to your instance, and `this` to the
// element, so for instance you can call your `onPageLoad`
// and pass it the element as a second argument:
return self.onPageLoad(event, this);
// Within the call to `onPageLoad`, `this` will be your instance
}, false);
}
(如果“闭包”对你来说是个新名词,别担心,closures are not complicated。)
闭包选项的完整示例:
var myExtension = {
init: function() {
var self = this;
// The event can be DOMContentLoaded, pageshow, pagehide, <b style="color:black;background-color:#99ff99">load</b> or unload.
if(gBrowser) {
gBrowser.addEventListener("DOMContentLoaded", function(event) {
return self.onPageLoad(event, this);
}, false);
}
},
onPageLoad: function(aEvent, aElement) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
var win = doc.defaultView; // win is the window for the doc
alert("<b style="color:black;background-color:#a0ffff">page</b> is loaded \n" +doc.location.href);
// This now works
Firefox.Console.log(this.userName);
// If you needed the `this` that Firefox gives the event handler
// (the tab or whatever), it's accessible via `aElement`
},
anotherMethod: function (){
this.userName = 'UserName';
}
}
window.addEventListener("<b style="color:black;background-color:#99ff99">load</b>", function() { myExtension.init(); }, false);