I’m using classic OOP code from Mozilla
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, 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);
//OOPs, error here, username is undefined
Firefox.Console.log(this.userName);
},
anotherMethod: function (){
this.userName = 'UserName';
}
}
window.addEventListener("<b style="color:black;background-color:#99ff99">load</b>", function() { myExtension.init(); }, false);
The general question is how can initialize and user public variables in my class?
You know, this in this class is some browser’s object (tab), but not a current class and I can’t assign this.win = doc.defaultView and use later like this.win.userName = 'UserName'
A couple of options:
Using
Function#bind:I believe in a Firefox extension you should have most if not all ES5 features available to you, which means you can use
Function#bindto make sure your event handler gets called withthisset to your instance. E.g.:Within the call to
onPageLoad,thiswill refer to your instance. You won’t have access to the normalthisFirefox gives the event handler (the tab or whatever).Fuller example of the
bindoption:Using a closure:
If I’m mistaken about ES5 in Firefox extensions, or if you want to have access to the
thisthat the event handler would normally receive, you can readily use a closure to do the same thing:(If “closure” is a new term to you, don’t worry, closures are not complicated.)
Fuller example of the closure option: