Blog

Blog

PHODAL

JavaScript DSL 流畅接口(使用链式调用)

认真研究了一会DSL,发现了这么几件有趣的事,JavaScript用得最多的一个东西怕是链式调用 (方法链,即Method Chaining)。 有意思的是Martin Flower指出:

I've also noticed a common misconception - many people seem to equate fluent interfaces with Method Chaining. Certainly chaining is a common technique to use with fluent interfaces, but true fluency is much more than that.

很多人将链式调用等同于流畅接口。然而链式调用是流畅接口的一种常用方法,真实的流畅接口不止这么一点点。

DSL 流畅接口

流畅接口的初衷是构建可读的API,毕竟代码是写给人看的。

类似的,简单的看一下早先我们是通过方法级联来操作DOM

var btn = document.createElement("BUTTON");        // Create a <button> element
var t = document.createTextNode("CLICK ME");       // Create a text node
btn.appendChild(t);                                // Append the text to <button>
document.body.appendChild(btn);                    // Append <button> to <body>

而用jQuery写的话,便是这样子

$('<span>').append("CLICK ME");

等等

于是回我们便可以创建一个简单的示例来展示这个最简单的DSL

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();

然而这看上去像是表达式生成器。

DSL 表达式生成器

表达式生成器对象提供一组连贯接口,之后将连贯接口调用转换为对底层命令-查询API的调用。

这样的API,我们可以在一些关于数据库的API中看到:

var query =
  SQL('select name, desc from widgets')
   .WHERE('price < ', $(params.max_price), AND,
          'clearance = ', $(params.clearance))
   .ORDERBY('name asc');

链式调用有一个问题就是收尾,同上的代码里面我们没有收尾,这让人很迷惑。。加上一个query和end似乎是一个不错的结果。

其他

方法级联

表示如下:

a.b();
a.c();

关于我

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

微信公众号(Phodal)

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

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

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

开源深度爱好者

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

联系我: h@phodal.com

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

标签