使用匿名函数||闭包 实现局部变量避免变量的全局污染html
(function(){})()
window.$=window.jQuery
function jQuery(){ return new jQuery.prototype.init() } jQuery.prototype.init=function(){ return this; } jQuery.prototype.init.prototype = jQuery.prototype //让init建立出来的实例都拥有jQuery原型prototype的方法
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.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(){} })
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(selector){ var str = typeof selector; if(str==="function"){ jQuery.ready(selector); //若是是一个函数 就当ready的回调函数执行 } } if(str==="object"){ this[0] = selector; this.length = 1; }
每次函数执行 都返回 this当前执行对象web