你有没有看过JQuery 1.4源代码的内幕,并注意到它是如何以下列方式封装的:
(function( window, undefined ) {
//All the JQuery code here
...
})(window);
Run Code Online (Sandbox Code Playgroud)
我读过一篇关于JavaScript Namespacing的文章和另一篇名为" 一对重要的Parens "的文章,所以我知道这里发生了什么.
但我以前从未见过这种特殊的语法.在那undefined做什么?为什么window需要通过然后再次出现?
老实说,我不知道如何缩短标题.
我通过研究SlidesJS插件的来源学习了如何编写jQuery 插件.当我遇到一些新的东西时,我只是问了我的好朋友谷歌,而且大部分时间都得到了满意的答案.老实说,我从来没有做过多少努力.我所知道的$是(可能)是一个简写的jQuery对象构造函数,$()并且jQuery()只要包含jQuery,它就是同样的东西.
不过,最近,我试图了解jQuery背后的科学以及如何编写一个好的 jQuery插件.我遇到了一篇非常好的文章,其中作者列出了几个用于创建jQuery插件的模板.由于其余部分太复杂,我无法理解,我喜欢第一个:轻量级的开始.现在,这是所述模板的代码.
/*!
* jQuery lightweight plugin boilerplate
* Original author: @ajpiano
* Further changes, comments: @addyosmani
* Licensed under the MIT license
*/
// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;(function ( $, window, document, undefined ) {
// undefined …Run Code Online (Sandbox Code Playgroud)