qiuhongbingo / blog

Writing something in Issues.
https://github.com/qiuhongbingo/blog/issues
3 stars 0 forks source link

jQuery 中的对象思想,$ 到底是个什么 #16

Open qiuhongbingo opened 4 years ago

qiuhongbingo commented 4 years ago
// 神奇的 $
$('p') // 返回的是数组
$('p').addClass() // 数组哪来的 addClass???
$.ajax() // $ 还是个对象???

// 翻了一下 jQuery 的源码(删减)
var jQuery = (function() {
  var $

  // ...

  $ = function(selector, context) {
    return function(selector, context) {
      var dom = []
      // dom.__proto__ 指向了 $.fn
      // $.fn 是包含了多种方法的对象集合,因此返回的结果(dom)可以在其原型链上找到 addClass 这样的方法
      dom.__proto__ = $.fn

      // ...

      return dom
    }
  }

  $.fn = {
    addClass: function() {
      // ...
    }
    // ...
  }

  // 同时 ajax 方法直接挂载在构造函数 $ 上,它是一个静态属性方法
  $.ajax = function() {
    // ...
  }

  return $
})()

window.jQuery = jQuery
window.$ === undefined && (window.$ = jQuery)

// 把上面的翻译成 ES6,比较好理解了
class $ {
  static ajax() {
    // ...
  }

  constructor(selector, context) {
    this.selector = selector
    this.context = context

    // ...
  }

  addClass() {
    //  ...
  }
}