9

前言

自己搭建了个仿jQuery的原型设计,JQuery的原型设计也是按这样来实现的,简单的说就是让_mJQ.init的原型对象和_mJQ的原型对象共用,然后new 一个_mJQ.init,很容易理解吧

正文

(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;
})

测试结果

clipboard.png


flayPig
460 声望379 粉丝

attemp to do something that is defferent.