最近更新
阅读排行
读过本文章的之后读了
关注本站

jQuery是如何实现链式调用的

阅读:10202 次   编辑日期:2014-05-05

目录:

概述:

如果在工作中经常用到jQuery的话,为了方便肯定会经常运用链式调用,例如#("#uw3c").show().html("uw3c");。那么为什么在同一个ID上面既可以show(),又可以html()呢? 这又是如何实现的呢,今天我们简单的来解析一下。

初步解析:

如果我要单个调用很简单,首先先看下面的代码:
    function auto(){}
        auto.prototype = {
            setName:function(name){
                this.name = name;
            },
            setAge:function(age){
                this.age = age;
            }
        }
        var setFun = new auto();
        alert(JSON.stringify(setFun));//{}
        setFun.setName("uw3c");//单个调用
        setFun.setAge(1);//单个调用
        alert(JSON.stringify(setFun));//{"name":"uw3c","age":1}
上面的代码中,首先alert的结果是空对象,之后调用了原形中方法之后,给对象setFun赋上了新的属性。这个大家都应该知道原因,如果你还不知道原因,请阅读 《关于prototype和constructor》

进一步解析:

看了上面的代码,单个调用的方法应该明白了,但是如何链式调用呢?看下面的代码:
    function auto(){}
        auto.prototype = {
            setName:function(name){
                this.name = name;
                return this;
            },
            setAge:function(age){
                this.age = age;
                return this;
            }
        }
        var setFun = new auto();
        alert(JSON.stringify(setFun));//{}
        setFun.setName("uw3c").setAge(1);//链式调用
        alert(JSON.stringify(setFun));//{"name":"uw3c","age":1}
上面的代码中,首先alert的结果依然是空对象,之后链式调用之后的结果跟之前单个调用的结果是一样的。
这是为什么呢?没错,每次调用完方法都返回this,不就都等于是在setFun上面调用方法了吗~
如果还不明白,就看看下面的代码:
    setFun.setName("uw3c") == this;//因为setName方法返回this,这里this == setFun。
    setFun.setName("uw3c").setAge(1) == this.setAge(1) == setFun.setAge(1);
将本篇文章分享到:
top