最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Can someone explain this javascript pattern used in the Twitter Bootstrap plugins to me? - Stack Overflow

programmeradmin1浏览0评论

I was looking at the jQuery plugins for Twitter Bootstrap and saw that they were all defined using a pattern like this:

!function($) {
  // code here

  // plugin definition here

} ( window.jQuery || window.ender);

This looks like a variation of the immediately executing anonymous function (anonymous closure):

(function($) {
  // code here

}(jQuery));

Can someone explain what the Bootstrap variation does and why? Is this a better way to write an anonymous closure?

Thanks!

I was looking at the jQuery plugins for Twitter Bootstrap and saw that they were all defined using a pattern like this:

!function($) {
  // code here

  // plugin definition here

} ( window.jQuery || window.ender);

This looks like a variation of the immediately executing anonymous function (anonymous closure):

(function($) {
  // code here

}(jQuery));

Can someone explain what the Bootstrap variation does and why? Is this a better way to write an anonymous closure?

Thanks!

Share Improve this question asked Jan 20, 2012 at 23:30 PeterPeter 12.7k3 gold badges36 silver badges39 bronze badges 4
  • 1 I think the only difference is that it saves you a character... Oh, and makes the pattern obscure. – Jordão Commented Jan 20, 2012 at 23:33
  • 2 @Jordão: Avoiding the () helps avoid bugs like this one – user1106925 Commented Jan 20, 2012 at 23:42
  • @am not i am: thanks for pointing that out. I'd still not use this idiom though, as it's not the proper way to fix that kind of bug. – Jordão Commented Jan 21, 2012 at 1:23
  • @Jordão: I wouldn't call it an improper fix. Irrespective of the bug, I still don't use () to create an IIFE. The bug is a bination of JS only having function scope, having ASI, and overloading the () syntax. It's up to the individual developer as to how they want to deal with it. Inserting a semi-colon is one option. – user1106925 Commented Jan 21, 2012 at 2:21
Add a ment  | 

1 Answer 1

Reset to default 11
//  |---1. makes the function as part of an expression 
//  |                             so it can be immediately invoked
//  v
    !function($) {
//            ^
//            |___4. references what was passed, window.jQuery or window.ender

      // code here

      // plugin definition here

    } ( window.jQuery || window.ender); // <---2. immediately invoke the function 
//         ^                ^
//         |________________|_______3. pass window.jQuery if it exists, 
//                                                      otherwise window.ender

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论