仿写jQuery总结

闭包

使用匿名函数||闭包 实现局部变量避免变量的全局污染html

(function(){})()

window全局方法

window.$=window.jQuery

jQuery无new化操做

function jQuery(){
    return new jQuery.prototype.init()
}
jQuery.prototype.init=function(){
    return this;
}
jQuery.prototype.init.prototype = jQuery.prototype
//让init建立出来的实例都拥有jQuery原型prototype的方法

ecah与回调函数

jQuery.prototype.each = function(fn){
    for(var i=0;i<this.length;i++){
        fn(this[i])
    }
}
//把this里面的元素传入到回调函数 执行一遍
jQuery.prototype.toggleClass = function(val){
    this.each(function(elem){
        elem.classlist.toggle(val)
    })
}

jQuery扩展插件

  1. 全局方法 $.ajax()
  2. 对象方法 $(".container").fullpage()
jQuery.fn = jQuery.prototype;
jQuery.extend = jQuery.fn.extend = function(options){
    var target = this;
    //jQuery.extend this指向jQuery和jQuery.fn.extend this指向实例
    for(var k in options){
        target[k] = options[k];
        //执行前拷贝
    }
}
jQuery.extend({
    trim:function(str){
        return str,trim();
    }
})
jQuery.fn.extend({
    show:function(){},
    hide:function(){}
})

文档加载的属性

  • img.onload 图片开始加载
  • document.addEventListener(“DOMContentLoaded”) 文档内容已经加载
  • window.onload

等待执行

jQuery.ready = function(fn){
    if(jQuery.isReady){
        fn();
    }else{
        setTimeout(function(){
            jQuery.ready(fn)
        },10)
    }
    //等待递归执行 若是超时能够报错
}
jQuery.ready(function(){});
//初始化调用

参数的多态

$(function(){
    $("h1").on("click",function(){
        $(this).toggleClass("red").toggleClass("light");
    })
})
  • ( ) ()参数 函数: (function(){})||字符串:$(“p”)||对象 $(this)
function(selector){
    var str = typeof selector;
    if(str==="function"){
        jQuery.ready(selector);
        //若是是一个函数 就当ready的回调函数执行
    }
}
if(str==="object"){
   this[0] = selector;
   this.length = 1;
}

链式调用

每次函数执行 都返回 this当前执行对象web