jQuery源码分析-03构造jQuery对象-工具函数

2020-05-19 07:26:09易采站长站整理

// browser event has already occurred.
if ( document.readyState === “complete” ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
// 兼容事件,通过检测浏览器的功能特性,而非嗅探浏览器
if ( document.addEventListener ) {
// Use the handy event callback
// 使用较快的加载完毕事件
document.addEventListener( “DOMContentLoaded”, DOMContentLoaded, false );
// A fallback to window.onload, that will always work
// 注册window.onload回调函数
window.addEventListener( “load”, jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
// 确保在onload之前触发onreadystatechange,可能慢一些但是对iframes更安全
document.attachEvent( “onreadystatechange”, DOMContentLoaded );
// A fallback to window.onload, that will always work
// 注册window.onload回调函数
window.attachEvent( “onload”, jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren’t supported. They return false on IE (#2968).
// 是否函数
isFunction: function( obj ) {
return jQuery.type(obj) === “function”;
},
// 是否数组
// 如果浏览器有内置的 Array.isArray 实现,就使用浏览器自身的实现方式,
// 否则将对象转为String,看是否为”[object Array]”。
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === “array”;
},
// A crude way of determining if an object is a window
// 简单的判断(判断setInterval属性)是否window对象
isWindow: function( obj ) {
return obj && typeof obj === “object” && “setInterval” in obj;
},
// 是否是保留字NaN
isNaN: function( obj ) {
// 等于null 或 不是数字 或调用window.isNaN判断
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
// 获取对象的类型
type: function( obj ) {
// 通过核心API创建一个对象,不需要new关键字
// 普通函数不行
// 调用Object.prototype.toString方法,生成 “[object Xxx]”格式的字符串
// class2type[ “[object ” + name + “]” ] = name.toLowerCase();
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || “object”;
},