我正在查看
Twitter Bootstrap的jQuery插件,看到它们都是使用这样的模式定义的:
!function($) { // code here // plugin definition here } ( window.jQuery || window.ender);
这看起来像是立即执行的匿名函数(匿名闭包)的变体:
(function($) { // code here }(jQuery));
有人可以解释Bootstrap变体的作用和原因吗?这是编写匿名闭包的更好方法吗?
谢谢!
解决方法
// |---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