函数也是对象,因此$.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 的 root 方法定义如下(仅显示相关部分):
(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 的实际实现感兴趣,请查看带注释的源代码: