js方法链(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
原型链与方法链在某些方面上是差不多的,不同的地方或许在于
1.原型链是需要用原型
2.方法链则是用方法
一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu