JQuery - $, JQuery, Window.load, JQuery.ready

开篇以前偶然间看到和这篇文章有关的Stackoverflow的一个thread,在这里摘录。 java

$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready
 alert("document is ready");
});


$(window).load(function() {
 // executes when complete page is fully loaded, including all frames, objects and images
 alert("window is loaded");
});
//All this three are having a same functionality

$(function(){
}); 

jQuery(document).ready(function(){
});

$(document).ready(function(){
});

在理解JQuery以前有必要理解一下Javascript基于对象的概念。 jquery

prototype ide

The function jQuery.fn.init is the one that is executed when you call jQuery(".some-selector") or $(".some-selector"). You can see this in this snippet from jquery.js: this

jQuery = window.jQuery = window.$ = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }

So, in fact, the line you mention is critical to how jQuery allows the addition of functionality to jQuery objects, both inside jQuery itself and from plugins. This is the line: spa

jQuery.fn.init.prototype = jQuery.fn;

By assigning jQuery.fn as the prototype of this function (and because the first snippet uses 'new' to treat jQuery.fn.init as a constructor), this means the functionality added via jQuery.fn.whatever is immediately available on the objects returned by all jQuery calls. prototype

So for example, a simple jQuery plugin might be created and used like this: code

jQuery.fn.foo = function () { alert("foo!"); }; jQuery(".some-selector").foo();

When you declare 'jQuery.fn.foo' on the first line what you're actually doing is adding that function to the prototype of all jQuery objects created with the jQuery function like the one on the second line. This allows you to simple call 'foo()' on the results of the jQuery function and invoke your plugin functions. 对象

In short, writing jQuery plugins would be more verbose and subject to future breakage if the implementation details changed if this line didn't exist in jQuery. three

$到底怎么执行的? ip

查看JQuery.js发现下面的代码

// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
相关文章
相关标签/搜索