Một trong những phần hay nhất tôi đã tìm thấy mã nguồn rõ ràng và súc tích là nguồn jQuery. Cho dù bạn có thích Javascript hay không, nó tạo ra một trường hợp tuyệt vời chống lại những người ủng hộ mã số "là tài liệu".
Có rất nhiều nhận xét nhưng nó không phải là tác phẩm nghệ thuật ascii và bạn có thể thấy lý do rõ ràng - ý kiến giúp bạn biết chính xác những gì đang cố gắng đạt được.
Một ví dụ (full source):
đang
(function(){
var
// Will speed up references to window, and allows munging its name.
window = this,
// Will speed up references to undefined, and allows munging its name.
undefined,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
jQuery = window.jQuery = window.$ = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context);
},
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/;
jQuery.fn = jQuery.prototype = {
init: function(selector, context) {
// Make sure that a selection was provided
selector = selector || document;
// Handle $(DOMElement)
if (selector.nodeType) {
this[0] = selector;
this.length = 1;
this.context = selector;
return this;
}
// Handle HTML strings
if (typeof selector === "string") {
// Are we dealing with HTML string or an ID?
var match = quickExpr.exec(selector);
// Verify a match, and that no context was specified for #id
if (match && (match[1] || !context)) {
// HANDLE: $(html) -> $(array)
if (match[1])
selector = jQuery.clean([ match[1] ], context);
// HANDLE: $("#id")
else {
var elem = document.getElementById(match[3]);
// Handle the case where IE and Opera return items
// by name instead of ID
if (elem && elem.id != match[3])
return jQuery().find(selector);
...
Nguồn
2010-01-11 15:20:34
Hầu hết các nhận xét đều có thể tránh được. "mã là tài liệu" không phải là về việc xả rác mã với các bình luận, thực sự. Martin fowler đã chứng ngộ tôi khi tôi đọc nhận xét đó là mùi mã. – rpattabi
Tôi thích hầu hết những nhận xét đó. Họ theo kịp với chính sách bình luận của tôi không nêu rõ TÔI đang làm gì nhưng TẠI SAO. –
@sebstian chính xác, không có ý kiến bạn sẽ không biết tại sao 'window = this' đang được sử dụng. @ ragu.pattabi bạn đang đề cập đến điều này: http://martinfowler.com/bliki/CodeAsDocumentation.html? Anh ta không đề cập đến bất cứ điều gì về ý kiến, chỉ là đoạn mã rõ ràng đó là tự ghi lại tài liệu. –