views:

102

answers:

2
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%5Fstarted%5Fwith%5Fextension%5Fdevelopment

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?

+3  A: 

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);
jldupont
jldupont. can you please answer my last question in the question comments too? thanks!
Delirium tremens
@Delirium: JS is not like Java: you don't need to declare strictly a function. JS will look for the method "onLoad" on the object "Helloworld" that's all. It does not look for method "onLoad(e)" i.e. JS doesn't care about "function signatures".
jldupont
A: 

You can change the onLoad if you want to have a parameter, it's just an example onLoad. It's JavaScript, after all, not C/C++ etc.

Gyuri