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

来源:网络 责任编辑:栏目编辑 发表时间:2013-07-02 01:27 点击:

 

为了写起来方便,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

    相关新闻>>

      发表评论
      请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
      用户名: 验证码:点击我更换图片
      最新评论 更多>>

      推荐热点

      • Gb2312转utf-8编码的方法(vbs+js)
      • 如何使用Ajax技术开发Web应用程序(1)
      • js跳转路径问题
      • JavaScript模仿桌面窗口
      • 用js检测两个线段是否相交
      • 运用JavaScript构建你的第一个Metro式应用程序(on Windows
      • 我知道的JavaScript -- 设计模式(桥接)应用之 – 验证器
      • 我是如何去了解jquery的(六),案例之幻灯片轮换
      • Jquery封装幻灯片效果
      网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
      Copyright © 2008-2015 计算机技术学习交流网. 版权所有

      豫ICP备11007008号-1