Ответ 1
Функции также являются объектами, поэтому $.each
можно определить аналогично объекту.
JavaScript - это прототип языка. Для jQuery это означает, что каждый экземпляр $
наследует методы из jQuery.prototype
. См. Примечания
Очень грубая демонстрация, чтобы добиться аналогичного поведения:
(function() { // Closure to not leak local variables to the global scope
function f(a, b) {
//Do something
}
// Prototype. All properties of f.prototype are inherited by instances of f.
// An instance of f can be obtained by: new f, new f(), Object.create(f)
f.prototype.removeClass = function(a) {
return a;
};
function $(a, b) {
return new f(a, b); // <--- "new f" !
}
$.each = function(a) {
alert(a);
};
window.$ = $; // Publish public methods
})();
//Tests (these do not represent jQuery methods):
$.each("Foo"); // Alerts "Foo" (alert defined at $.each)
alert($().removeClass('Blabla'));// Alerts "Blabla"
Примечания
Корневой метод jQuery определяется следующим образом (показаны только части релевантов):
(function(win) {
var jQuery = function (selector, context) {
return new jQuery.fn.init(selector, context, rootjQuery);
};
//$.fn = jQuery.fn is a shorthand for defining "jQuery plugins".
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( /* ..parameters.. */ ) {
//.... sets default properties...
}
//....other methods, such as size, get, etc...
//.... other properties, such as selector, length, etc...
};
jQuery.fn.removeClass = function() { // (Actually via jQuery.fn.extend)
// ... method logic...
}; //...lots of other stuff...
win.$ = win.jQuery = jQuery; //Publish method
})(window);
Преимущество метода prototype
заключается в том, что очень легко цепочки методов и свойств. Например:
$("body").find("div:first").addClass("foo");
Метод реализации этой функции может быть:
$.fn.find = function(selector) {
...
return $(...);
};
Если вас интересует реальная реализация jQuery, посмотрите на аннотированный исходный код:
- jQuery core - Определения конструктора и базовых методов.
-
jQuery.fn.extend
используется для добавитьremoveClass
и т.д. в jQuery. - jQuery 1.7.1.