Javascript中的方法链(Method Chaining)介绍
在寻找如何设计一个JavascriptAPI的时候,发现了MethodChaining这个东西,方法链,看上去似乎很强大,也挺有意思的,而这个东西也是过去我们经常看到的。。
JavascriptMethodChaining
在维基百科上有这样的解释:
Methodchaining,alsoknownasnamedparameteridiom,isacommonsyntaxforinvokingmultiplemethodcallsinobject-orientedprogramminglanguages.Eachmethodreturnsanobject,allowingthecallstobechainedtogetherinasinglestatement.Chainingissyntacticsugarwhicheliminatestheneedforintermediatevariables.Amethodchainisalsoknownasatrainwreckduetotheincreaseinthenumberofmethodsthatcomeoneafteranotherinthesamelinethatoccursasmoremethodsarechainedtogetheeventhoughlinebreaksareoftenaddedbetweenmethods.
拿翻译工具翻译了一下:
方法链,也被称为命名参数法,是在面向对象的编程语言调用的调用多个方法的通用语法。每一个方法返回一个对象,允许电话连接到一起,在一个单一的声明。链接是语法糖,省去了中间变量的需要。方法链也被称为火车残骸中由于方法来相继发生的同一行以上的方法都锁在即使换行通常添加方法间的数量增加。
MethodChaining使用
目测对于方法链用得最多的,应该就是jQuery了。
//chaining
$("#person").slideDown('slow')
.addClass('grouped')
.css('margin-left','11px');
我们可以用这样的用法来调用这个。jQuery严重依赖于链接。这使得它很容易调用的几个方法相同的选择。这也使得代码更清晰和防止执行相同的选择几次(提高性能)。没有方法链的时候则是下面的样子
varp=$('#person');
p.slideDown('slow');
p.addClass('grouped');
p.css('margin-left','11px');
看上去和设计模式中的builder很像,不同的是,这里的p是方法,而不是一个类。
Javascript方法链示例
在之前我们说到Javascript高阶函数的时候,说到的print('Hello')('World'),而这种用法的结果可能会变成这样子。
functionf(i){
returnfunction(e){
i+=e;
returnfunction(e){
i+=e;
returnfunction(e){
alert(i+e);
};
};
};
};
f(1)(2)(3)(4);//10
这是网上的一个例子,然而也是我上一次写链式调用的作法。看上去弱爆了。
varfunc=(function(){
return{
add:function(){
console.log('1');
return{
result:function(){
console.log('2');
}
}
}
}
})();
func.add().result();