jquery 定义函数-jQuery 鞋工厂函数 $()

2023-09-01 0 5,537 百度已收录

jQuery 中最常用的鞋厂函数是 $()。 它本质上是一个DOM对象,但是它使用的方法都封装在jQuery中,所以我们不能通过$()来使用JavaScript。 同样的 DOM 对象在 jQuery 上也无法使用技巧

我们从$开始,引出jQuery的整个结构

以jQuery 1.11.3版本为例,$作为函数名出现的地方是在源码的最后:

	window.jQuery = window.$ = jQuery;

其中jquery 定义函数,jQuery是上面定义的一个函数,出现在源码第70行

	jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		// Need init if jQuery is called (just allow error to be thrown if not included)
		return new jQuery.fn.init( selector, context );
	}

该函数相当于鞋工厂函数,内部返回一个对象,这样就可以不用new方法来创建jQuery对象

所以new $().xxx和$().xxx没有区别jquery 定义函数,这也符合jQuery“write less, do more”的设计理念

源代码第2882行:

	// Give the init function the jQuery prototype for later instantiation
	init.prototype = jQuery.fn;

init的原型对象被替换为jQuery.fn,实际上是被jQuery函数本身的原型对象jQuery.prototype替换。

源代码第89行:

	jQuery.fn = jQuery.prototype

这样我们就可以轻松的编写jQuery的扩展方法了

举个反例:

	jQuery.fn.alertMsg = function(msg){
		alert('msg');
	}

使用:

	$().alertMsg('Hello World!');

jQuery的整体结构就差不多到这里了

下面是一个简化版的jQu​​ery框架,方便理解

	(function () {
	    function jQuery(selector) {
	        return new jQuery.prototype.init(selector);
	    }
	    // jQuery对象的构造函数
	    jQuery.prototype.init = function (selector) {
	       
	    }
	    // jQuery原型上的css方法
	    jQuery.prototype.css = function (config) {
	        
	    }
	    // 将jQuery原型上的方法都放到init的原型链上
	    jQuery.prototype.init.prototype = jQuery.prototype;
	    window.$ = window.jQuery = jQuery;
	})();

关系图:

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悟空资源网 jquery jquery 定义函数-jQuery 鞋工厂函数 $() https://www.wkzy.net/game/185641.html

常见问题

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务