简体   繁体   English

有人能解释一下Twitter Bootstrap插件中使用的这个javascript模式吗?

[英]Can someone explain this javascript pattern used in the Twitter Bootstrap plugins to me?

I was looking at the jQuery plugins for Twitter Bootstrap and saw that they were all defined using a pattern like this: 我正在查看Twitter Bootstrap的jQuery插件,看到它们都是使用这样的模式定义的:

!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? 有人可以解释Bootstrap变体的作用和原因吗? Is this a better way to write an anonymous closure? 这是编写匿名闭包的更好方法吗?

Thanks! 谢谢!

//  |---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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM