本身搭建了個仿jQuery的原型設計,JQuery的原型設計也是按這樣來實現的,簡單的說就是讓_mJQ.init的原型對象和_mJQ的原型對象共用,而後new 一個_mJQ.init,很容易理解吧css
(function(global, factory) { if (typeof global.document === 'undefined') { throw new Error('the environment must have a window Object with document !') } // 若環境存在則執行factory factory(global); })(typeof window !== 'undefined' ? window : this, function (window) { var _mJQ = function (selector) { return new _mJQ.init(selector); } // 初始化 _mJQ.init = function(selector) { // 進行selector匹配,好比class,attr,id等... if (selector === '#test') { const elem = document.getElementById('test') this.elem = elem return this } return this } // 讓init的原型對象指向_mJQ的原型 _mJQ.init.prototype = _mJQ.prototype = { // 功能 each: function() { // 循環 }, html: function() {}, css: function (name, value) { console.log(this) this.elem.style[name] = value } } // 設置contructor指向問題 Object.defineProperty(_mJQ.prototype, 'constructor', { enumerable: false, value: _mJQ }) // 掛載到window window.$ = window.mJQ = _mJQ; })