jQuery中$(document).ready()的特殊写法2013-04-16看书时注意到下面两条语句的功效是相同的,
$(function(){alert("hello!");}); $(document).ready(function(){alert("hello!");});
这个特殊写法就是用$()代替$(document).ready(),类似于(有差异)window.onload弹出个窗口:

查看jQuery1.8.3源代码,是这样封装的:
(function( window, undefined ) { /*...jQuery源代码全部都在这里了...*/})( window );
下列语句把封装在内部的jQuery先赋给window.$,紧接着再赋给window.jQuery。这意味着在实际使用时window.$和window.jQuery是一回事。因为$这个符号只有1个字母,比jQuery短,所以更常用一些,但要注意到$非jQuery所独有,节约字母的代价是增加了命名冲突的风险。
// Expose jQuery to the global object window.jQuery = window.$ = jQuery;
下面是jQuery的初始化语句(注意到此时函数并未执行):
// Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor "enhanced" return new jQuery.fn.init( selector, context, rootjQuery ); }
找到jQuery.fn的定义,这是一个对象,其中有一个叫init的函数元素:
jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } /*...以下省略...*/
继续下去,init中有一段逻辑:
// HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); }