JavaScript 中的链式调用

最近在看 jQuery 的源码,正好看到异步队列 Deferred 的实现,联想到链式调用的实现。

实现

在 JS 的代码中,我们有时会看到形如这样的代码:

Function.prototype.method = function (name, func) {
  this.prototype[name] = func;
  return this;                              // 注意这个地方
};

注意到上面 function 中的 return this;,它的存在就是为了返回当前调用方法的对象实例。
借此我们可以进行链式调用。

样例代码

function AnimalSounds() {}

AnimalSounds.prototype.cow = function() {
    alert("moo");
    return this;
}

AnimalSounds.prototype.pig = function() {
    alert("oink");
    return this;
}

AnimalSounds.prototype.dog = function() {
    alert("woof");
    return this;
}

var sounds = new AnimalSounds();

sounds.cow();
sounds.pig();
sounds.dog();

sounds.cow().pig().dog();                     // 链式调用

参考链接

https://stackoverflow.com/questions/8300844/what-does-return-this-do-within-a-javascript-function

你可能感兴趣的:(JavaScript 中的链式调用)