入口函数的作用:等待页面加载完毕,有一个独立的作用域。
原生JS 和 jQuery 入口函数区别:
(1)JS的window.onload事件必须要等到所有内容,以及外部图片之类的文件加载完之后,才会去执行。
(2)JQuery入口函数是在所有标签加载完之后,就会去执行。
jQuery基本结构
jQuery是一个闭包
之前有写过闭包:Mr.J--JS学习(闭包及IIFE)
(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对象中返回