您的位置:首页 > Web前端 > JQuery

jQuery 源码分析 -1 $是什么?

2010-04-22 21:17 423 查看
本源码使用当前的 jQuery 1.3.2 版本,下载时间 2009-4-25,下载网站:jquery.com。

一个函数

1 /*!
2 * jQuery JavaScript Library v1.3.2
3 * http://jquery.com/ 4 *
5 * Copyright (c) 2009 John Resig
6 * Dual licensed under the MIT and GPL licenses.
7 * http://docs.jquery.com/License 8 *
9 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
10 * Revision: 6246
11 */
12 (function(){

4376 })();

省略掉中间的内容,可以看到从第 12 行到 4376 行,jQuery 代码可以简化为如上的代码。
也就是定义了一个匿名的函数,然后执行这个函数。
在这个匿名函数中完成其他的定义和操作,这样可以避免与系统的其他函数同名造成的命名冲突问题。相当于一个私有的作用域。

$ 是什么?jQuery 又是什么?

13 var
14 // Will speed up references to window, and allows munging its name.
15 window = this,
16 // Will speed up references to undefined, and allows munging its
17 name.
18 undefined,
19 // Map over jQuery in case of overwrite
20 _jQuery = window.jQuery,
21 // Map over the $ in case of overwrite
22 _$ = window.$,
23
24 jQuery = window.jQuery = window.$ = function( selector, context ) {
25 // The jQuery object is actually just the init constructor 'enhanced'
26 return new jQuery.fn.init( selector, context );
27 },

通过这段代码,可以看到 $,jQuery 是 window 对象上自定义的一个成员,这个成员指向了一个匿名函数,以后可以通过window 对象的 $ 或者 jQuery 来使用这个函数。

这个函数返回了一个通过 jQuery.fn.init 函数定义的对象。说明通过 jQuery 得到的对象其实是一个 jQuery.fn.init 函数创建的对象,那么,以后通过 jQuery.fn.init 的原型定义的函数或者属性都可以被通过 jQuery 创建的对象来使用。

jQuery.fn 是什么?

35 jQuery.fn = jQuery.prototype = {

538 };

从 35 行到 538 行,为 jQuery.fn 的定义,jQuery.fn 就是 jQuery 所指向的函数的原型对象。所以在 jQuery 的原型上定义的函数就可以通过 jQuery.fn 来使用了。

而上边的 jQuery.fn.init 就是 jQuery 函数原型对象上的一个函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: