jQuery is highly focused on the DOM and provides a nice abstraction around it. In doing so, it makes use of various well known design patterns which just hit me yesterday. One obvious example would be the Decorator pattern. The jQuery object provides new and additional functionality around a regular DOM object.

例如,DOM有一个原生的insertBefore方法,但没有相应的insertAfter方法.有多种实现available来填补这一空白,jQuery就是这样一个库,它提供了以下功能:

$(selector).after(..)
$(selector).insertAfter(..)

There are many other examples of the Decorator pattern being heavily used in jQuery.

您注意到库本身还包含哪些其他设计模式的例子,无论大小?此外,请提供一个使用该模式的示例.

Making this a community wiki as I believe that various things people love about jQuery can be traced back to well known design patterns, just that they are not commonly referred to by the pattern's name. There is no one answer to this question, but cataloging these patterns will provide a useful insight into the library itself.

推荐答案

Lazy Initialization:

$(document).ready(function(){
    $('div.app').myPlugin();
});

Adapter or wrapper

$('div').css({
    opacity: .1 // opacity in modern browsers, filter in IE.
});

Facade

// higher level interfaces (facades) for $.ajax();
$.getJSON();
$.get();
$.getScript();
$.post();

Observer

// jQuery utilizes it's own event system implementation on top of DOM events.
$('div').click(function(){})
$('div').trigger('click', function(){})

Iterator

$.each(function(){});
$('div').each(function(){});

Strategy

$('div').toggle(function(){}, function(){});

Proxy

$.proxy(function(){}, obj); // =oP

Builder

$('<div class="hello">world</div>');

Prototype

// this feels like cheating...
$.fn.plugin = function(){}
$('div').plugin();

Flyweight

// CONFIG is shared
$.fn.plugin = function(CONFIG){
     CONFIG = $.extend({
         content: 'Hello world!'
     }, CONFIG);
     this.html(CONFIG.content);
}

Jquery相关问答推荐

使用 howler.js 中的变量播放多种声音

将元素附加到每个函数 jQuery

Visual Studio - 将文本粘贴到 cshtml 中会删除文本

JQuery:$.get 不是函数

将 jquery 元素转换为 html 元素

禁用提交按钮,直到所有字段都有值

.slice(0) 在这里有什么意义?

Jquery .on('scroll')在滚动时不触发事件

如何知道字体(@font-face)是否已经加载?

谷歌图表重绘/zoom 窗口调整大小

jQuery用另一个类替换一个类

jquery-ui datepicker更改z-index

验证外部脚本是否已加载

获取元素的底部和右侧位置

使用 jQuery 拖放防止单击事件

jQuery 插件:添加回调功能

jQuery:如果页面底部有外部 JS,为什么要使用 document.ready?

如何从 jQuery UI datepicker 获取日期

将多个 JavaScript 文件合并为一个 JS 文件

在某个点停止固定位置滚动?