这种设计模式在 JavaScript/jQuery 中被称为什么?
我正在查看 SlickGrid 的 JavaScript 源代码。
我注意到 slick.grid.js 具有以下结构:
(function($) {
// Slick.Grid
$.extend(true, window, {
Slick: {
Grid: SlickGrid
}
});
var scrollbarDimensions; // shared across all grids on this page
////////////////////////////////////////////////////////////////////////////
// SlickGrid class implementation (available as Slick.Grid)
/**
* @param {Node} container Container node to create the grid in.
* @param {Array,Object} data An array of objects for databinding.
* @param {Array} columns An array of column definitions.
* @param {Object} options Grid options.
**/
function SlickGrid(container,data,columns,options) {
/// <summary>
/// Create and manage virtual grid in the specified $container,
/// connecting it to the specified data source. Data is presented
/// as a grid with the specified columns and data.length rows.
/// Options alter behaviour of the grid.
/// </summary>
// settings
var defaults = {
...
};
...
// private
var $container;
...
////////////////////////////////////////////////////////////////////////
// Initialization
function init() {
/// <summary>
/// Initialize 'this' (self) instance of a SlickGrid.
/// This function is called by the constructor.
/// </summary>
$container = $(container);
...
}
////////////////////////////////////////////////////////////////////////
// Private & Public Functions, Getters/Setters, Interactivity, etc.
function measureScrollbar() {
...
}
////////////////////////////////////////////////////////////////////////
// Public API
$.extend(this, {
"slickGridVersion": "2.0a1",
// Events
"onScroll": new Slick.Event(),
...
// Methods
"registerPlugin": registerPlugin,
...
});
init();
}
}(jQuery));
为了简洁和清晰起见,省略了一些代码,但这应该可以让您了解总体思路。
以下内容的目的是什么:
(function($) { // code }(jQuery));
这是我见过讨论的模块模式吗?这是为了保持全局命名空间干净吗?$.extend()
行的含义是什么?:顶部的$.extend(true, window, { // code });
看起来有与“命名空间”有关;什么是命名空间?看起来底部$.extend(this, { // code });
用于公开“公共”成员和函数?如何定义私有函数或变量?如果您愿意,您将如何初始化多个“SlickGrid”?他们会分享多少内容以及如何互动?请注意“构造函数”函数:
function SlickGrid(...) { // code }
。有哪些关于这种风格编码的书籍、链接和其他资源?谁发明了它?
谢谢! ♥
I was looking over the JavaScript source code for SlickGrid.
I've noticed that slick.grid.js has the following structure:
(function($) {
// Slick.Grid
$.extend(true, window, {
Slick: {
Grid: SlickGrid
}
});
var scrollbarDimensions; // shared across all grids on this page
////////////////////////////////////////////////////////////////////////////
// SlickGrid class implementation (available as Slick.Grid)
/**
* @param {Node} container Container node to create the grid in.
* @param {Array,Object} data An array of objects for databinding.
* @param {Array} columns An array of column definitions.
* @param {Object} options Grid options.
**/
function SlickGrid(container,data,columns,options) {
/// <summary>
/// Create and manage virtual grid in the specified $container,
/// connecting it to the specified data source. Data is presented
/// as a grid with the specified columns and data.length rows.
/// Options alter behaviour of the grid.
/// </summary>
// settings
var defaults = {
...
};
...
// private
var $container;
...
////////////////////////////////////////////////////////////////////////
// Initialization
function init() {
/// <summary>
/// Initialize 'this' (self) instance of a SlickGrid.
/// This function is called by the constructor.
/// </summary>
$container = $(container);
...
}
////////////////////////////////////////////////////////////////////////
// Private & Public Functions, Getters/Setters, Interactivity, etc.
function measureScrollbar() {
...
}
////////////////////////////////////////////////////////////////////////
// Public API
$.extend(this, {
"slickGridVersion": "2.0a1",
// Events
"onScroll": new Slick.Event(),
...
// Methods
"registerPlugin": registerPlugin,
...
});
init();
}
}(jQuery));
Some code has been omitted for brevity and clarity, but this should give you the general idea.
What is the purpose of the the following:
(function($) { // code }(jQuery));
Is this the module pattern that I've seen talked about? Is this meant to keep the global namespace clean?What do the
$.extend()
lines mean?: The top$.extend(true, window, { // code });
looks like it has to do with a "namespace"; what's a namespace? It looks like the bottom$.extend(this, { // code });
is used to exposed 'public' members and functions? How would you define a private function or variable?How would you initialize multiple "SlickGrids" if you wanted to? How much would they share and how would they interact? Note the "constructor" function:
function SlickGrid(...) { // code }
.What are some books, links, and other resources on coding in this style? Who invented it?
Thanks! ♥
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个 jQuery 插件。
(function($) { // code }(jQuery));
为您提供一个新的函数作用域,这样您的名称就不会转储到全局作用域中。通过将 jQuery 作为 $ 传递,您可以使用 $ 简写,即使其他 Javascript 库使用 $ 也是如此。$.extend
是一种 jQuery 方法,用于将属性从一个对象复制到另一个对象。第一个参数true
表示它应该是深副本而不是浅副本。通过扩展window
,创建新的全局属性,在本例中为Slick
。底部的
$.extend(this,...)
位于大写函数 SlickGrid 中。SlickGrid
旨在用作构造函数,在这种情况下,this
将是新创建的对象,因此此extend
将属性添加到物体。他们实际上是公众成员。在此代码示例中,measureScrollbar
是私有的:它仅对此函数中定义的代码可见,在函数外部不可见。您可以使用以下方法创建多个网格:
在您显示的代码中,这两个实例唯一共享的是
scrollBarDimensions
变量。This is a jQuery plugin.
(function($) { // code }(jQuery));
gives you a new function scope so your names are not dumped into the global scope. Passing jQuery as $ lets you use the $ shorthand even if other Javascript libraries use $.$.extend
is a jQuery method to copy properties from one object to another. The first argumenttrue
means it should be a deep rather than a shallow copy. By extendingwindow
, new global properties are created, in this case,Slick
.The
$.extend(this,...)
at the bottom is in a capitalized function SlickGrid.SlickGrid
is meant to be used as a constructor, in which casethis
will be the newly-created object, so thisextend
is adding properties to the object. They are effectively public members. In this code sample,measureScrollbar
is private: it is only visible to the code defined in this function, not outside it.You can create a number of grids with:
In the code you've shown, the only thing these two instances will share is the
scrollBarDimensions
variable.这是一个闭包。它基本上保证了“//代码”内部的所有内容免受外部事物的影响。你传递了 jQuery 和 $,但是有更多知识的人将不得不解释为什么这是必要的。
这是一个 jQuery 函数,它将接受两个对象并将它们合并在一起。用第二个对象 {Slick: {Grid: SlickGrid}} 替换第一个对象“window”。这意味着如果有一个带有 Grid:Null 的窗口对象,它现在将等于 Grid:SlickGrid。
添加 true 作为第一个参数意味着它也将替换嵌套对象:
如果您使用大量对象来存储信息,这非常有用。
不确定 #3 是什么意思,但请查看 http://960.gs 以获得良好的网格系统。
JavaScript the Good Parts 是一本很棒的书。 John Resig 的《Pro JavaScript》也是一本可以带您超越基础知识的好书。
This is a closure. It basically keeps everything inside it "// code" safe from things outside it. You pass in jQuery and the $, but someone with more knowledge will have to explain why that is necessary.
This is a jQuery function that will take two objects and merge them together. Replacing the first object "window" with the second object {Slick: {Grid: SlickGrid}}. This means if there is a window object with Grid:Null it would now equal Grid:SlickGrid.
Adding true as a first parameter means it will replace nested objects as well:
This is useful if you are using a lot of objects to store information.
Not sure what you mean by #3, but look at http://960.gs for a good grid system.
JavaScript the Good Parts is a great book. Pro JavaScript by John Resig is also a good book to take you beyond the basics.
简而言之,您的示例中的人刚刚编写了某种 jQuery 插件...请查看 jquery.com 的 PLUGINS 部分,以获取有关如何编写插件代码的更多参考资料。它们简单、直接且探索起来很有趣。
Simply put, guy in your example just wrote jQuery plug-in of sorts... Check PLUGINS section of jquery.com for more references to sources on how to code plugins. They are simple, straightforward and fun to explore.
对于第一个问题,这个构造是一种允许 jQuery 与其他可能使用 $ 函数的库共存的方法,但仍然使用 $ 在代码块中引用 jQuery。
整个包包装在一个以
$
作为参数的函数调用中。运行时唯一的“主要”活动是使用jQuery
作为参数调用该函数,这为本地参数提供了对众所周知的全局jQuery
的引用$
,它屏蔽$
可能具有的任何全局值。For the first question, this construct is a way to allow jQuery to coexist with other libraries which may use the $ function, but still use $ to reference jQuery within a code block.
The entire package is wrapped in a function call with
$
as a parameter. The only "main" activity when this is run is to call that function withjQuery
as an argument, this giving a reference to the well-known globaljQuery
to the local parameter$
, which masks any global value that$
may have.1)当JS文件加载时,该函数立即被调用。它接收 jquery 实例作为参数,并使其在内部作为“$”可用。所有代码都封装在该函数中,因此(除非您忘记了尚未声明的变量前面的 var),不会污染全局命名空间。
2) 第二个对象的所有属性都复制到第一个对象,这里是“window”,它也是 Web 浏览器中的全局命名空间对象。因此这段代码没有多大意义。它假装封装,但效果恰恰相反。第二次调用 $.extend 也没有多大意义。这并没有错,我只是认为代码“假装”。
4) 我强烈建议您观看 Douglas Crockford 的视频,网址为 http: //developer.yahoo.com/yui/theater/
Crockford 是一位 JS 大神,非常有名(在严肃的 JS 程序员中) - 而且听起来也很有趣:)
1) That function is invoked immediately when the JS file is loaded. It receives the jquery instance as parameter and makes it available internally as "$". All code is encapsulated in that function so (unless you forget a var in front a yet undeclared variable) nothing pollutes the global namespace.
2) All properties of the 2nd object are copied to the 1st object, here "window", which also is the global namespace object in a web browser. Therefore this code does not make much sense. It pretends to encapsulate but does the opposite. Neither does the second invocation of $.extend make all that much sense. It's not wrong, I just think the code "pretends".
4) I very highly recommend you check out the videos from Douglas Crockford at http://developer.yahoo.com/yui/theater/
Crockford is a JS god, very famous (among serious JS programmers) - and in addition great fun to listen to :)