Javascript链式调用案例

jQuery用的就是链式调用。像一条连接一样调用方法。
链式调用的核心就是return this;,每个方法都返回对象本身。

下面是简单的模拟jQuery的代码,

<script>
    window.$ = function (id) {
        return new _$(id);
    }
    function _$(id) {
        this.elements = document.getElementById(id);
    }
    _$.prototype = {
        constructor: _$,
        hide: function () {
            console.log('hide');
            return this;
        },
        show: function () {
            console.log('show');
            return this;
        },
        getName: function (callback) {
            if (callback) {
                callback.call(this, this.name);
            }
            return this;
        },
        setName: function (name) {
            this.name = name;
            return this;
        }
    }
    $('test').setName('helloworld').getName(function (name) {
        console.log(name);
    }).show().hide().show().hide().show();
</script>

helloworld
show
hide
show
hide
show

原文地址:https://www.cnblogs.com/jiqing9006/p/6210648.html