zoukankan      html  css  js  c++  java
  • jQuery源码基本框架

    jQuery1.6将近9000行的代码,看看都头晕,把代码简化成这样看就清晰多了:

    (function( window, undefined ) {

    var jQuery = (function() {

         var jQuery = function( selector, context ) {
         return new jQuery.fn.init( selector, context, rootjQuery );
          };

      jQuery.fn = jQuery.prototype = {};

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

          jQuery.extend = jQuery.fn.extend =function(){};

          jQuery.extend({});

      return jQuery;
    })();

    window.jQuery = window.$ = jQuery;
    })(window);

    一、从最外层看:(function( window, undefined ) {})(window);在命名空间定义函数,是为了避免变量名污染,这样既不会与外部产生冲突,也可以通过命名函数进行调用,例如

    var msg=function(){};
    msg={"a":function(){alert(2)}};
    (function(window){var msg=function(){};msg={"a":function(){alert(1)}};window.$=msg})(window); 
    $.a();//1
    msg.a();//2

    二、从内部看jquery:

    var jQuery = (function() {

       var jQuery = function( selector, context ) {
           return new jQuery.fn.init( selector, context, rootjQuery );
          };

      jQuery.fn = jQuery.prototype = {init:function( selector, context, rootjQuery ){}};

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

          jQuery.extend = jQuery.fn.extend =function(){};

          jQuery.extend({});

      return jQuery;
    })();

    一开始定义var jQuery=function( selector, context )){return new jQuery.fn.init( selector, context, rootjQuery );}};jQuery是一个Function对象可以执行。

    接着定义jQuery.fn = jQuery.prototype = {init:function( selector, context, rootjQuery ){}};jQuery是Function对象,这个时候执行,它不会继承jQuery.prototype的属性,这个时候jQuery.init是undefind;我们调用$("XX")也是通过调用匿名函数jQuery=function( selector, context ) {return new jQuery.fn.init( selector, context, rootjQuery );},通过实例化jQuery.fn.init()对象,从而获得jQuery.fn = jQuery.prototype ={}里的属性和方法。

         jQuery并不是直接实例化本身,而是通过实例化 jQuery.fn.init获得对象。但是jQuery.fn本身也是Object实例化对象,jQuery.fn.init是它的一个方法,不能通过new jQuery.fn.init( selector, context, rootjQuery )进行实例化,所以通过jQuery.fn.init.prototype = jQuery.fn;把jQuery.fn.init的原型链指向jQuery.fn,并通过new jQuery.fn.int()实例化对象,继承{init:function( selector, context, rootjQuery ){}}属性和方法,并返回给jQuery,这时候jQuery才真正拥有继承{init:function( selector, context, rootjQuery ){}}属性和方法。

      jQuery.extend = jQuery.fn.extend =function(){};所以到这里我们就可以知道这两个方法的区别,通过jQuery.fn.extend扩展的方法或者属性,是挂在jQuery.fn.init原型链,只有通过实例化jQuery对象才能调用,例如:$("img").attr("src");而通过jQuery.extend扩展,实际是扩展jQuery的静态方法或者属性,可以直接调用。例如:$.trim();

       jQuery.extend({});给jQuery对象定义了一些方法和属性

  • 相关阅读:
    CSS——精灵图与背景图片定位
    CSS——text-indent
    CSS——样式隐藏
    CSS——规避脱标流和vertical-align
    CSS——盒子居中显示
    CSS——img
    CSS——position
    CSS——样式初始化
    CSS——清除浮动
    CSS——float
  • 原文地址:https://www.cnblogs.com/liubingna/p/3447478.html
Copyright © 2011-2022 走看看