读jQuery.js源码心得

  • jQuery框架使用方式的特点

    • 不使用new关键字直接调用jQuery函数返回jQuery对象

    • jQuery对象中包含DOM元素

    • 该对象可链式调用内置属性和方法(API)


  • jQuery用法示例
  // html
  <div></div>

  // js
  $('div')

  // 返回结果
  jQuery.fn.init [div, prevObject: jQuery.fn.init(1)]
    0: div
    length: 1
    prevObject: jQuery.fn.init [document]
    __proto__: Object(0)

  • jQuery的整体架构分析

    • 全面使用( 面向对象编程 && 原型链编程 )

    • 实例方法都挂载到原型上

    • 工具方法都挂载到函数上

      // 利用闭包封装jQuery防止污染全局变量
      (function(global, factory){
        factory(global);
      }(typeof window !== 'undefined' ? window : this, function(window){
        // 挂载到window
        window.jQuery = window.$ = jQuery;
    
        // 调用该方法返回jq对象
        function jQuery(selector) {
          return new jQuery.prototype.init(selector);
        }
    
        jQuery.prototype = {
          // init为构造函数构造jq对象
          init: function(selector) {
            ...
          },
          // 内置属性和API举例
          css: function() {
            console.log('css');
            // 实现链式调用
            return this;
          },
          html: function() {
            console.log('html');
            // 实现链式调用
            return this;
          }
        }
    
        // 使jQuery.prototype可挂载一些内置属性方法,jq对象可顺着原型链访问
        jQuery.prototype.init.prototype = jQuery.prototype
      }));
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章