JavaScript DSL 流畅接口(使用链式调用)实例
认真研究了一会DSL,发现了这么几件有趣的事,JavaScript用得最多的一个东西怕是链式调用(方法链,即MethodChaining)。有意思的是MartinFlower指出:
I'vealsonoticedacommonmisconception-manypeopleseemtoequatefluentinterfaceswithMethodChaining.Certainlychainingisacommontechniquetousewithfluentinterfaces,buttruefluencyismuchmorethanthat.
很多人将链式调用等同于流畅接口。然而链式调用是流畅接口的一种常用方法,真实的流畅接口不止这么一点点。
DSL流畅接口
流畅接口的初衷是构建可读的API,毕竟代码是写给人看的。
类似的,简单的看一下早先我们是通过方法级联来操作DOM
varbtn=document.createElement("BUTTON"); //Createa<button>element
vart=document.createTextNode("CLICKME"); //Createatextnode
btn.appendChild(t); //Appendthetextto<button>
document.body.appendChild(btn); //Append<button>to<body>
而用jQuery写的话,便是这样子
$('<span>').append("CLICKME");
等等
于是回我们便可以创建一个简单的示例来展示这个最简单的DSL
Func=(function(){
this.add=function(){
console.log('1');
returnthis;
};
this.result=function(){
console.log('2');
returnthis;
};
returnthis;
});
varfunc=newFunc(); func.add().result();