5

I've been seeing a familiar pattern in JavaScript/jQuery plugin development (Modernizr uses this first example), by which the functions are nicely wrapped in an IIFE and are globally defined on the window object. I am asking is if it's a good idea to make your plugins/scripts accessible globally by doing the following:

window.myPluginName = (function (window, document, undefined) {
  // Plugin logic
})(window, document);

I ask this because some scripts/plugins need accessing in the DOM where they're called, or elsewhere in a document/file. Inside the plugins I also see this sometimes:

(function (window, document, undefined) {
  window.myPluginName = function () {
    // Plugin logic
  }
})(window, document);

And even this:

(function (window, document, undefined) {
  var myPluginName = function () {
    // Plugin logic
  }
  window.myPluginName = myPluginName;
})(window, document);

I am really intrigued as to the differences behind the setups, and if someone with more experience than I would be kind enough to provide some advice on which is best to use for development. Thank you!

4

1 回答 1

2

简短的回答:使用对您最有意义的那个。

更长的答案:唯一的区别是分配发生的位置,但在功能方面它们都是等效的。它们中没有一个比另一个有任何优势或劣势。

注意:就目前而言,最后两个不起作用,因为window在函数内部未定义。但我假设您实际上会将window对象作为参数传递给 IIFE。

于 2013-08-12T11:10:41.863 回答