我想使用这种模式是新的热点,但我不明白它的优点是什么,我不理解范围的含义.
模式:
(function(window, document, undefined){
window.MyObject = {
methodA: function() { ... },
methodB: function() { ... }
};
})(window, document)
Run Code Online (Sandbox Code Playgroud)
所以我对此有几个问题.
封装像这样的对象有什么特别的优势吗?
为什么窗口和文档被输入而不是正常访问?
为什么undefined要传递这个?
将我们正在创建的对象直接附加到窗口是一个特别好的主意吗?
我已经习惯了我称之为Crockford风格的Javascript封装(因为我把它从Douglas Crockford Javascript视频中删除了).
NameSpace.MyObject = function() {
// Private methods
// These methods are available in the closure
// but are not exposed outside the object we'll be returning.
var methodA = function() { ... };
// Public methods
// We return an object that uses our private …Run Code Online (Sandbox Code Playgroud) 老实说,我不知道如何缩短标题.
我通过研究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) 以下JavaScript是什么意思?为什么函数嵌入在()中?
(function() {
var b = 3;
a += b;
}) ();
Run Code Online (Sandbox Code Playgroud)