开发者

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

var Helloworld = {
  onLoad: function() {
    // initia开发者_运维知识库lization 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?


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜