js 实现链式调用

1 什么是链式调用

下面的示例即链式调用,像链表一样依次调用对象的多个方法:

1
$(document).addClass('hello').removeClass('hello')

2 链式调用的实现

2.1 在对象方法的最后返回对象本身

在方法的最后返回对象本身,即可实现链式调用,如下例:

1
2
3
4
5
6
7
8
9
10
11
12
var obj = {
a: function () {
console.log("a");
return this;
},
b: function () {
console.log("b");
return this;
},
};

obj.a().b();