代码分析jQuery四种静态方法使用

jQery每一个方法都有对应代码解析,非常详细,具有介绍请看下文:

isFunction方法

用于测试是否为函数的对象

示例:

rush:js;"> function stub() { } var objs = [ function () {},{ x:15,y:20 },null,stub,"function" ]; jQuery.each(objs,function (i) { var isFunc = jQuery.isFunction(objs[i]); $("span:eq( " + i + ")").text(isFunc); })

运行结果:

代码如下:

源码分析:

<div class="jb51code">
<pre class="brush:js;">
// 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";
},

首先就告诉你自从1.3版本就有bug,一些dom方法函数例如alert在ie里面会返回false,看了下这个bug,因为toString方法和valueOf方法都会被重写所以有人就提出了用instanceof方法检测但是在ie6还是有问题。目前为止这个bug还没有关闭具体大家可以从参考官网bug页因为我分析的是1.7.1所以就先按照这个版本来,这个方法就是简单的调用type方法判断其返回结果是否为字符串function

isArray方法

用于测试是否为数组的对象

示例:

<div class="jb51code">
<pre class="brush:js;">
$("b").append( " + $.isArray([]) );//true

isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},

跟isFunctoin一样直接使用type方法的返回结果

isNumeric方法

确定它的参数是否是一个数字。

$.isNumeric() 方法检查它的参数是否代表一个数值。如果是这样,它返回 true。否则,它返回false。该参数可以是任何类型的

示例:

rush:js;"> $.isNumeric("-10"); // true $.isNumeric(16); // true $.isNumeric(0xFF); // true $.isNumeric("0xFF"); // true $.isNumeric("8e5"); // true (exponential notation string) $.isNumeric(3.1415); // true $.isNumeric(+10); // true $.isNumeric(0144); // true (octal integer literal) $.isNumeric(""); // false $.isNumeric({}); // false (empty object) $.isNumeric(NaN); // false $.isNumeric(null); // false $.isNumeric(true); // false $.isNumeric(Infinity); // false $.isNumeric(undefined); // false

源码分析:

代码如下:

这个方法不是判断Number类型而是看起来像数字的类型只要传进去的参数包含数字那么就会返回true,首先使用parseFloat方法把参数转为数组,此方法会保留参数中的数字部分过滤掉其他部分,如果结果不是NaN也没有超过最大值就是true否则返回false

isWindow方法

用于测试是否为window对象

<div class="jb51code">
<pre class="brush:js;">
<div class="codetitle"><a style="CURSOR: pointer" data="94200" class="copybut" id="copybut94200" onclick="doCopy('code94200')"> 代码如下:

<div class="codebody" id="code94200">isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},

一种粗略的方法判断对象是window,如果满足传进来的是对象而且具有setInterval方法则认为该对象为window对象,现在这方法已经改为判断是否是窗口对象了具体以后在分析。希望大家能够喜欢以上内容所述。

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...