函数也是对象,所以$.each
可以用与对象类似的方式来定义。
JavaScript is a prototypical language. For jQuery, this means that every instance of $
inherits methods from jQuery.prototype
.See Notes
一个非常粗略的演示,以实现类似的行为:
(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"
Notes
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 的实际实现感兴趣,请查看带注释的源代码:
-
jQuery 核心 https://github.com/jquery/jquery/blob/master/src/core.js#L1- 构造函数和基本方法的定义。
-
jQuery.fn.extend
习惯于add removeClass等到 jQuery https://github.com/jquery/jquery/blob/master/src/attributes.js#L13.
-
jQuery 1.7.1 http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js.