Search code examples
javascriptmozillafirefox-addon

What does this code (from a Mozilla Add-on tutorial) do?


var Helloworld = {
  onLoad: function() {
    // initialization code
    this.initialized = true;
  },

  onMenuItemCommand: function() {
    window.open("chrome://helloworld/content/hello.xul", "", "chrome");
  }
};

window.addEventListener("load", function(e) { Helloworld.onLoad(e); }, false); 

http://kb.mozillazine.org/Getting_started_with_extension_development

I don't understand the function(e) { Helloworld.onLoad(e); part. I think it passes an event parameter e to the onLoad function, but the onLoad function doesn't have onLoad: function(e) {} to receive e, so what's going on?


Solution

  • Just defines an anonymous function: the said function will will be called when the event load is triggered.

    Note that in JavaScript, the function declaration isn't strict. One can call a function with parameters even if the declaration doesn't explicitly show such. In other words, there is no such thing as a "function signature" (like in Java, C++ etc.). The JavaScript interpreter will only call the "hasmethod" method on the object to determine if "method X" is implemented.

    var Helloworld = {
    
      // parameters can be sent to "onload" but they will be ignored.
      onLoad: function() {
        // initialization code
        this.initialized = true;
      },
    
      onMenuItemCommand: function() {
        window.open("chrome://helloworld/content/hello.xul", "", "chrome");
      }
    };
    
    // attach an event handler to the event "load".  Pass the event variable "e"
    // even though the receiving function will ignore it. 
    window.addEventListener("load", function(e) { Helloworld.onLoad(e); }, false);