jq小小封装

本文详细介绍了jQuery的核心——一个轻量级的JavaScript库,它简化了DOM操作、动画和Ajax交互。通过封装构造函数、原型和全局访问,jQuery实现了高效的功能调用和链式操作。文章还展示了如何模拟jQuery的click和toggle方法,并讨论了其实现的闭包机制,以确保代码的健壮性和性能。此外,还展示了jQuery的extend方法,用于扩展jQuery对象的功能。
摘要由CSDN通过智能技术生成

什么是jq

jQuery是一个优秀的JavaScript库,是一个凭借简洁的语法和跨平台的兼容性,极大地简化了JavaScript开发人员遍历HTML文档,操作DOM,执行动画和开发Ajax的操作。jQuery封装了很多预定义的对象和函数。其理念:write less,do more.

如何对jq进行封装

定义JQuery构造函数的显示原型
在这里插入图片描述
定义jQuery原型上的方法
在这里插入图片描述
让new init 产生对象拥有JQuery显示原型上的所有方法

jQuery.fn.init.prototype = jQuery.fn;

全局访问jQuery与$

window.$ = window.jQuery = jQuery;
(function(window,undefind){
    function jQuery(){
        return new jQuery.prototype.init()
    }
    jQuery.prototype={
        constructor:jQuery,
        init:function(){
            console.log("初始化已完成")
        }
    }
    jQuery.prototype.init.prototype=jQuery.prototype
    window.jQuery=window.$=jQuery
})(window)

jQuery实质是一个闭包,通过代码可以看出外面用的是匿名函数的写法,把window当作实参传入了进去,这样的写法避免了全局变量的污染,保证安全性,当然也提供了入口函数

封装jq

jq方法
(function() {
	// 匿名函数自执行
	// jQ的构造函数
	function jQuery(selector) {
		// 返回new 一个初始化函数
		return new jQuery.fn.init(selector);
	}
	// 定义JQuery构造函数的显示原型
	jQuery.fn = jQuery.prototype = {
		constructor: jQuery,
		jquery: "9.0.0",
		length: 0,
		get(index) {
			return this[index];
		},
		/* click(callback){
			// 单击时候让this的每个元素执行callback回调函数
			for(var i=0;i<this.length;i++){
				this[i].addEventListener("click",callback);
			}
			// jq实现链式操作每个函数执行完毕都是返回this
			return this;
		}, */
		/* toggle(){
			// 遍历每个元素如果display不是none就隐藏,否则就显示
			for(var i=0;i<this.length;i++){
				if(this[i].style.display!="none"){
					this[i].style.display="none"
				}else{
					this[i].style.display="block";
				}
			}
			return this;
		}, */
		each(callback) {
			for (var i = 0; i < this.length; i++) {
				callback(this[i])
			}
			return this;
		},
		click(callback) {
			// item指向的被遍历的每个元素
			this.each(function(item) {
				// 让每个元素注册click事件 执行callback方法
				// 也就是click 括号里面的回调函数
				item.addEventListener("click", callback);
			})
			return this;
		},
		toggle() {
			this.each(function(item) {
				if (item.style.display != "none") {
					item.style.display = "none"
				} else {
					item.style.display = "block";
				}
			})
		}
	}

	var isReady = false;
	var readyList = [];
	document.addEventListener("DOMContentLoaded", function() {
		isReady = true;
		readyList.forEach(item => item());
		readyList = [];

	})

	// jq初始化函数
	jQuery.fn.init = function(selector) {
		if (typeof selector === "function") {
			if (!isReady) {
				selector()
			} else {
				readyList.push(selector)
			}
		} else {
			// 获取到选择列表
			var list = document.querySelectorAll(selector);
			// 当前对象的长度
			this.length = list.length;
			for (var i = 0; i < list.length; i++) {
				//遍历类别对 this赋值
				this[i] = list[i];
			}
		}

	}
	// 如何让new  init 产生对象拥有JQuery显示原型上的所有方法呢?
	jQuery.fn.init.prototype = jQuery.fn;
	// 全局对jQuery与$可以访问
	window.$ = window.jQuery = jQuery;

})()

jq方法的使用
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/jquery-9.0.0.js"></script>
		<script>
			$(function() {
				alert("jq已经加载完毕")
			})
			$(function() {
				alert("jq已经加载完毕2")
			})
		</script>
	</head>
	<body>
		<h1>jquery还是大哥吗?</h1>
		<p>是的</p>
		<h1>市场占用96.8%</h1>
		<button>切换</button>
		<script>
			// jq实现链式操作
			// 给button注册一个点击事件
			// each函数编写
			$("button").click(function() {
				// 让h1切换显示与隐藏
				$("h1").toggle().click(function() {
					alert(this.innerText);
				});
			})
			$(function() {
				alert("jq已经加载完毕3")
			})
		</script>
	</body>
</html>

效果展示

在这里插入图片描述
在这里插入图片描述

jq的extent方法

jQuery.extend( {

	// Unique for each copy of jQuery on the page
	expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),

	// Assume jQuery is ready without the ready module
	isReady: true,

	error: function( msg ) {
		throw new Error( msg );
	},

	noop: function() {},

	isPlainObject: function( obj ) {
		var proto, Ctor;

		// Detect obvious negatives
		// Use toString instead of jQuery.type to catch host objects
		if ( !obj || toString.call( obj ) !== "[object Object]" ) {
			return false;
		}

		proto = getProto( obj );

		// Objects with no prototype (e.g., `Object.create( null )`) are plain
		if ( !proto ) {
			return true;
		}

		// Objects with prototype are plain iff they were constructed by a global Object function
		Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
		return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
	},

	isEmptyObject: function( obj ) {
		var name;

		for ( name in obj ) {
			return false;
		}
		return true;
	},

	// Evaluates a script in a provided context; falls back to the global one
	// if not specified.
	globalEval: function( code, options, doc ) {
		DOMEval( code, { nonce: options && options.nonce }, doc );
	},

	each: function( obj, callback ) {
		var length, i = 0;

		if ( isArrayLike( obj ) ) {
			length = obj.length;
			for ( ; i < length; i++ ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		} else {
			for ( i in obj ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		}

		return obj;
	},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var ret = results || [];

		if ( arr != null ) {
			if ( isArrayLike( Object( arr ) ) ) {
				jQuery.merge( ret,
					typeof arr === "string" ?
						[ arr ] : arr
				);
			} else {
				push.call( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		return arr == null ? -1 : indexOf.call( arr, elem, i );
	},

	// Support: Android <=4.0 only, PhantomJS 1 only
	// push.apply(_, arraylike) throws on ancient WebKit
	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		for ( ; j < len; j++ ) {
			first[ i++ ] = second[ j ];
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, invert ) {
		var callbackInverse,
			matches = [],
			i = 0,
			length = elems.length,
			callbackExpect = !invert;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i < length; i++ ) {
			callbackInverse = !callback( elems[ i ], i );
			if ( callbackInverse !== callbackExpect ) {
				matches.push( elems[ i ] );
			}
		}

		return matches;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var length, value,
			i = 0,
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArrayLike( elems ) ) {
			length = elems.length;
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}
		}

		// Flatten any nested arrays
		return flat( ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// jQuery.support is not used in Core but other projects attach their
	// properties to it so it needs to exist.
	support: support
} );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值