Blog

Blog

PHODAL

Javascript Method Chaining 方法链

在寻找如何设计一个Javascript API的时候,发现了Method Chaining这个东西,方法链,看上去似乎很强大,也挺有意思的,而这个东西也是过去我们经常看到的。。

Javascript Method Chaining

在维基百科上有这样的解释:

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement.Chaining is syntactic sugar which eliminates the need for intermediate variables. A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained togethe even though line breaks are often added between methods.

拿翻译工具翻译了一下:

  方法链,也被称为命名参数法,是在面向对象的编程语言调用的调用多个方法的通用语法。每一个方法返回一个对象,允许电话连接到一起,在一个单一的声明。链接是语法糖,省去了中间变量的需要。方法链也被称为火车残骸中由于方法来相继发生的同一行以上的方法都锁在即使换行通常添加方法间的数量增加。

Method Chaining 使用

目测对于方法链用得最多的,应该就是jQuery了。

// chaining
$("#person").slideDown('slow')
   .addClass('grouped')
   .css('margin-left', '11px');

我们可以用这样的用法来调用这个。jQuery严重依赖于链接。这使得它很容易调用的几个方法相同的选择。这也使得代码更清晰和防止执行相同的选择几次(提高性能)。没有方法链的时候则是下面的样子

var p = $('#person');
p.slideDown('slow');
p.addClass('grouped');
p.css('margin-left', '11px');

看上去和设计模式中的builder很像,不同的是,这里的p是方法,而不是一个类。

Javascript 方法链示例

在之前我们说到Javascript 高阶函数 的时候,说到的print('Hello')('World'),而这种用法的结果可能会变成这样子。

function f(i){
  return function(e){
    i+=e;
    return function(e){
      i+=e;
      return function(e){
        alert(i+e);
      };
    };
  };
};
f(1)(2)(3)(4); //10

这是网上的一个例子,然而也是我上一次写链式调用的作法。看上去弱爆了。

var func = (function() {
    return{
        add: function () {
            console.log('1');
            return{
                result: function () {
                    console.log('2');
                }
            }
        }
    }
})();

func.add().result();

实际上应该在每个function都要有个return this,于是就有了:

Func = (function() {
    this.add = function(){
        console.log('1');
        return this;
    };
    this.result = function(){
        console.log('2');
        return this;
    };
    return this;
});

var func = new Func();
func.add().result();

当然我们也可以将最后的两句

var func = new Func();
func.add().result();

变成

new Func().add().result();

其他

最后作为一个迷惑的地方的小比较:

Method Chaining VS prototype Chaining

原型链与方法链在某些方面上是差不多的,不同的地方或许在于

  • 原型链是需要用原型
  • 方法链则是用方法

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签