Mr.J-- jQuery学习笔记(二十二)--入口函数

这篇博客探讨了jQuery的入口函数及其作用,对比了它与原生JS的window.onload事件的区别。文章详细介绍了jQuery的基本结构,解释了为何使用闭包以及其优势。接着,列举并解释了传入不同参数(如空值、HTML片段、选择器、数组等)时,jQuery如何创建和返回对象。最后进行了总结,明确了各种参数类型的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

入口函数的作用:等待页面加载完毕,有一个独立的作用域。

原生JS 和 jQuery 入口函数区别:

(1)JS的window.onload事件必须要等到所有内容,以及外部图片之类的文件加载完之后,才会去执行。

(2)JQuery入口函数是在所有标签加载完之后,就会去执行。

jQuery基本结构

jQuery是一个闭包

之前有写过闭包:Mr.J--JS学习(闭包及IIFE)

Mr.J--JS学习(闭包私有化)

(function test(){
    console.log("test");
})()

执行结果:test

对于下面的demo:

var num;
num = 10;
num = 20;
console.log(num);

执行结果一眼看出:20,后面的值会覆盖前面的值进行输出

jQuery为什么要使用闭包来实现?
          为了避免多个框架的冲突
jQuery如何让外界访问内部定义的局部变量
           window.xxx = xxx;

(function f1() {
	var num = 10;
	window.num = num;
})();
(function f2() {
	var num = 20;
})();
console.log(num);

对于上面的demo运行结果:

 jQuery为什么要给自己传递一个window参数?
           为了方便后期压缩代码
           为了提升查找的效率

自己存在值使用自己的,不存在则在函数外部找

var value = 20;
function f3() {
	 //var value = 10;
	console.log(value);
}
f3();

执行结果:20

var value = 20;
function f3() {
	var value = 10;
	console.log(value);
}
f3();

执行结果:10

jQuery为什么要给自己接收一个undefined参数?
           为了方便后期压缩代码

IE9以下的浏览器undefined可以被修改, 为了保证内部使用的undefined不被修改, 所以需要接收一个正确的undefined

undefined = 998;
console.log(undefined);

jQuery基本结构--demo

(function( window, undefined ) {
	var jQuery = function( ) {
		return new jQuery.prototype.init( );
	}
	jQuery.prototype = {
		constructor: jQuery
	}	
	jQuery.prototype.init.prototype = jQuery.prototype;
	window.jQuery = window.$ = jQuery;
})( window );

 

jQ入口函数传入不同参数得到的实例

传入 '' null undefined NaN  0  false

会返回一个空的jQuery对象给我们

console.log($());
console.log($(''));
console.log($(null));
console.log($(undefined));
console.log($(NaN));
console.log($(0));
console.log($(false));

传入html片段

会将创建好的DOM元素存储到jQuery对象中返回

console.log($('<p>1</p><p>2</p><p>3</p>'));

传入选择器

会将找到的所有元素存储到jQuery对象中返回

console.log($('li'));

传入数组

会将数组中存储的元素依次存储到jQuery对象中立返回

var arr = [1, 2, 3, 4, 5, 6];
console.log($(arr));

传入伪数组

会将数组中存储的元素依次存储到jQuery对象中立返回

var likeArr = {0:"yjk", 1:"33", 2:"male", length: 3};
console.log($(likeArr));

 console.log(typeof arr);
 console.log(typeof likeArr);
 console.log(arr.toString());
 console.log(likeArr.toString());
 console.log(({}).toString.apply(arr));

传入对象

会将传入的对象存储到jQuery对象中返回

function Person() {}
console.log($(new Person()));

传入DOM元素

会将传入的DOM元素存储到jQuery对象中返回

console.log($(document.createElement('div')));

传入基本数据类型

会将传入的基本数据类型存储到jQuery对象中返回

console.log($(123));

console.log($(true));

总结:

 1.传入 '' null undefined NaN  0  false, 返回空的jQuery对象
 2.字符串:
 代码片段:会将创建好的DOM元素存储到jQuery对象中返回
 选择器: 会将找到的所有元素存储到jQuery对象中返回
 3.数组:
 会将数组中存储的元素依次存储到jQuery对象中立返回
 4.除上述类型以外的:
 会将传入的数据存储到jQuery对象中返回

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值