winddow.$ = window.jQuery = function (selectorOrArray) { let elements = null if (typeof selectorOrArray === 'string') { elements = document.querySelectorAll(selectorOrArray) } elseif (selectorOrArray instanceofArray) { elements = selectorOrArray }
let api = { find(selector) { let array = []; for (let i = 0; i < elements.length; i++) { const elements2 = Array.from(elements[i].querySelectorAll(selector)); array.push(...elements2); } array.oldThis = this; returnjQuery(array); }, addClass(className) {}, }; return api; };
window.$ = window.jQuery = function (selectorOrArray) { let elements = null if (typeof selectorOrArray === 'string') { elements = document.querySelectorAll(selectorOrArray) } elseif (selectorOrArray instanceofArray) { elements = selectorOrArray }
const api = Object.create(jQuery.prototype) // 创建一个对象,这个对象的__proto__为括号里的 // Object.assign方法就是把{}中的对象都赋值给api // 相当于 api.elements = elements Object.assign(api, { elements: elements, // 把oldThis 存在这个对象里。 要不然别的方法访问不到 // find中返回的是新的jQuery对象,而selectorOrArray是有oldThis这个属性的 oldThis: selectorOrArray.oldThis, }) return api }