当前位置:编程学习 > JAVA >>

jQuery1.0源代码分析之get方法(六)

 

为了写起来方便,jQuery注册到$上。为了不和其他框架冲突,他先备份了$到_$上。

 

 

// Map over the $ in case of overwrite 

if ( $ ) 

    jQuery._$ = $; 

 

// Map the jQuery namespace to the '$'one 

var $ = jQuery; 

下面是jQuery的原型方法

 

 

jQuery.fn = jQuery.prototype = { 

    jquery: "$Rev: 509 $";, 

 

    size: function() { 

        return this.length; 

    }, 

 

    get: function( num ) { 

        // Watch for when an array (of elements) is passed in 

        if ( num && num.constructor == Array ) { 

 

            // Use a tricky hack to make the jQuery object 

            // look and feel like an array 

            this.length = 0; 

            [].push.apply( this, num ); 

             

            return this; 

        } else 

            return num == undefined ? 

 

                // Return a 'clean' array 

                jQuery.map( this, function(a){ return a } ) : 

 

                // Return just the object 

                this[num]; 

    }, 

 

jquey:代表版本号,也是判断一个对象是不是jquery的标志

size:返回jQuery对象的大小,jQuery对象是一个类数组对象,有length,可以索引下标,但是没有数组方法。

 

get:get方法很灵活,参数可有可无。不带参数返回一个jQuery对象数组;参数num为数字型,返回第num个元素;参数num为数组型,将num种的元素设置为jQuery对象元素。

 

 

代码的亮点就在

 

 

this.length = 0; 

[].push.apply( this, num ); 

this代表jQuery实例对象,设置属性length为0,然后用push方法,把num中的元素压进来。

这两句话缺一不可,这样处理完成后,就是类数组对象了,有length属性,可以迭代,但没有数组方法。

 

相当于下面代码:

 

 

var obj = new Object(); 

obj.length = 0; 

[].push.apply(obj, [1,2,3]); 

alert(obj.length); // 3   

 

 


作者 baozhifei
补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,