jQuery源代码分析

jQuery源代码中的一些设计的分析

参考的是早期版本:
https://ajax.microsoft.com/ajax/jquery/jquery-1.4.js

全局对象jQuery和$

(function( window, undefined ) {
  // Define a local copy of jQuery
  var jQuery = function( selector, context ) {
    return new jQuery.fn.init( selector, context );
  },
  ...
  // 暴露jQuery 为全局对象,当然它是一个类形式的对象,JS一切皆对象
  window.jQuery = window.$ = jQuery;
})(window);

jQuery无new构建对象

思路类似于

需要new的方式

var jQuery = function(selector, context) { //构造函数
  ...
} 
jQuery.prototype = { //原型对象
     funca:function(){console.log("funca");},
     funcb:function(){} 
} 
var $id1 = new jQuery("#id1"); 
$id1.funca(); // 输出funca 

无new方式

var jQuery = function(selector, context ) {     
    return new jQuery.fn.init( selector, context ); 
}; 
jQuery.fn = jQuery.prototype = {    
    init: function( selector, context ) {   /* 初始化代码 */ },     
    funca:function(){console.log("funca");}, 
    funcb:function(){} 
} 
jQuery("#id1").funca();

jQuery扩展的实现

jQuery.fn = jQuery.prototype = { 
  init: function( selector, context ) { 
  ... 
jQuery.extend = jQuery.fn.extend = function() {
  var target = arguments[0] || {}, i = 1, length = arguments.length, 
  ...

实现的思路类似于

扩展jQuery的两种方法,本质是扩展prototype

//Method A, 相当于jQuery.prototype.pluginA = function(){}
$.fn.pluginA = function(cfg){ //jQuery对象的扩展
    var $config={width:300,height:460,ratio:1.65,magnifier_radius:90}; 
    $.extend($config,cfg);     
}; 
$.pluginA = function(cfg){ //jQuery类的扩展
};
//Method B    
$.fn.extend({ //对象的扩展
    pluginB:function(){     
        $(this).css('background-color','pink'); 
    }    
});
$.extend({ // 类的扩展
});

$(function)的实现

它其实是document元素ready事件触发的一个Shortcut

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
...
// HANDLE: $(function)
        // Shortcut for document ready
        } else if ( jQuery.isFunction( selector ) ) {
            return rootjQuery.ready( selector );
        }
...
rootjQuery = jQuery(document);

jQuery事件的实现

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup error").split(" "), function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( fn ) {
        return fn ? this.bind( name, fn ) : this.trigger( name );
    };
...

noConflict

_jQuery = window.jQuery
_$ = window.$
jQuery.extend({ 
   noConflict: function( ) { 
       window.$ = _$; 
       ...

Leave a Reply

Your email address will not be published. Required fields are marked *