鈺樹霖楓 發表於 2025-10-13 14:00:00

JavaScript链式调用(基础篇)

<h2>一、什么是链式调用?</h2>
<h2>&nbsp;<strong>链式调用(Method Chaining)</strong>&nbsp;是一种让多个方法通过连续的“点操作符”调用的编码风格</h2>
<pre class="code-snippet__js" data-lang=""><code>// 示例:jQuery 的链式调用</code><code>$("#myDiv")</code><code>&nbsp; .css("color", "red")</code><code>&nbsp; .addClass("highlight")</code><code>&nbsp; .fadeOut(1000);</code></pre>
<p>链式调用的核心特点是:<strong>每个方法执行后返回对象本身</strong>(或其他对象),从而可以继续调用下一个方法。</p>
<p>&nbsp;</p>
<h2>二、如何实现链式调用?</h2>
<h2>&nbsp;</h2>
<h3>1. 基础实现原理</h3>
<p>在对象的方法中,通过&nbsp;<code>return this</code>&nbsp;返回当前对象,使后续方法可以继续调用。</p>
<p><strong>示例:一个计算器对象的链式调用</strong></p>
<pre class="code-snippet__js" data-lang=""><code>class Calculator {</code><code>&nbsp; constructor(value = 0) {</code><code>&nbsp; &nbsp; this.value = value;</code><code>&nbsp; }</code><code><br></code><code>&nbsp; add(num) {</code><code>&nbsp; &nbsp; this.value += num;</code><code>&nbsp; &nbsp; return this; // 关键点:返回当前对象</code><code>&nbsp; }</code><code><br></code><code>&nbsp; subtract(num) {</code><code>&nbsp; &nbsp; this.value -= num;</code><code>&nbsp; &nbsp; return this;</code><code>&nbsp; }</code><code><br></code><code>&nbsp; multiply(num) {</code><code>&nbsp; &nbsp; this.value *= num;</code><code>&nbsp; &nbsp; return this;</code><code>&nbsp; }</code><code><br></code><code>&nbsp; getResult() {</code><code>&nbsp; &nbsp; return this.value;</code><code>&nbsp; }</code><code>}</code><code><br></code><code>// 链式调用</code><code>const result = new Calculator(10)</code><code>&nbsp; .add(5) &nbsp; &nbsp; &nbsp; &nbsp;// 10 + 5 = 15</code><code>&nbsp; .subtract(3) &nbsp; // 15 - 3 = 12</code><code>&nbsp; .multiply(2) &nbsp; // 12 * 2 = 24</code><code>&nbsp; .getResult(); &nbsp;// 最终结果</code><code><br></code><code>console.log(result); // 输出 24</code></pre>
<h3>2. 关键点总结</h3>
<h3>&nbsp;</h3>
<ul class="list-paddingleft-1">
<li>
<p><strong>每个方法必须返回对象本身</strong>(<code>return this</code>)。</p>
</li>
<li>
<p>如果某个方法不需要返回对象(如&nbsp;<code>getResult()</code>),则不参与链式调用。</p>
</li>
<li>
<p>&nbsp;</p>
</li>
</ul>
<h2>三、链式调用的实际应用场景</h2>
<h2>&nbsp;</h2>
<h3>1. 处理数组的链式调用</h3>
<p>JavaScript 的数组方法(如&nbsp;<code>map</code>、<code>filter</code>、<code>reduce</code>)天然支持链式调用:</p>
<pre class="code-snippet__js" data-lang=""><code>const numbers = ;</code><code><br></code><code>const result = numbers</code><code>&nbsp; .map(num =&gt; num * 2) &nbsp; &nbsp;// </code><code>&nbsp; .filter(num =&gt; num &gt; 5) // </code><code>&nbsp; .reduce((sum, num) =&gt; sum + num, 0); // 24</code><code><br></code><code>console.log(result); // 输出 24</code></pre>
<h3>2. 自定义类的链式调用(如 UI 组件)</h3>
<pre class="code-snippet__js" data-lang=""><code>class Dialog {</code><code>&nbsp; constructor(text) {</code><code>&nbsp; &nbsp; this.text = text;</code><code>&nbsp; &nbsp; this.color = "black";</code><code>&nbsp; &nbsp; this.duration = 1000;</code><code>&nbsp; }</code><code><br></code><code>&nbsp; setColor(color) {</code><code>&nbsp; &nbsp; this.color = color;</code><code>&nbsp; &nbsp; return this;</code><code>&nbsp; }</code><code><br></code><code>&nbsp; setDuration(duration) {</code><code>&nbsp; &nbsp; this.duration = duration;</code><code>&nbsp; &nbsp; return this;</code><code>&nbsp; }</code><code><br></code><code>&nbsp; show() {</code><code>&nbsp; &nbsp; console.log(`显示弹窗:${this.text},颜色:${this.color},持续 ${this.duration}ms`);</code><code>&nbsp; }</code><code>}</code><code><br></code><code>// 链式调用配置弹窗</code><code>new Dialog("Hello!")</code><code>&nbsp; .setColor("blue")</code><code>&nbsp; .setDuration(2000)</code><code>&nbsp; .show();</code></pre>
<h2>四、链式调用的优缺点</h2>
<h2>&nbsp;</h2>
<h3>优点:</h3>
<ol class="list-paddingleft-1">
<li>
<p><strong>代码简洁</strong>:减少重复代码,提高可读性。</p>
</li>
<li>
<p><strong>流程清晰</strong>:按顺序执行多个操作,逻辑一目了然。</p>
</li>
</ol>
<h3>缺点:</h3>
<ol class="list-paddingleft-1">
<li>
<p><strong>调试困难</strong>:链式调用中若某一步出错,难以定位具体位置。</p>
</li>
<li>
<p><strong>返回类型限制</strong>:必须返回对象本身,不适合需要返回其他值的场景。</p>
</li>
</ol>
<p>&nbsp;</p>
<h2>五、常见问题与解决方案</h2>
<h2>&nbsp;</h2>
<h3>问题1:忘记写&nbsp;<code>return this</code></h3>
<pre class="code-snippet__js" data-lang=""><code>// 错误示例:未返回 this,链式调用中断</code><code>class BadExample {</code><code>&nbsp; methodA() {</code><code>&nbsp; &nbsp; console.log("A");</code><code>&nbsp; &nbsp; // 没有 return this!</code><code>&nbsp; }</code><code>}</code><code><br></code><code>const obj = new BadExample();</code><code>obj.methodA().methodB(); // 报错:TypeError</code></pre>
<h3><code><strong>解决</strong>:确保每个链式方法都返回&nbsp;<code>this</code>。</code></h3>
<p>&nbsp;</p>
<h2>总结</h2>
<h2>&nbsp;</h2>
<ul class="list-paddingleft-1">
<li>
<p>链式调用的核心是&nbsp;<strong>方法返回对象本身</strong>(<code>return this</code>)。</p>
</li>
<li>
<p>适用于需要按顺序执行多个操作的场景(如配置对象、数据处理)。</p>
</li>
<li>
<p>注意避免在需要返回其他值的方法中使用链式调用。</p>
</li>
</ul>
<p>掌握链式调用后,你的代码会变得更加简洁和优雅!</p>

</div>
<div id="MySignature" role="contentinfo">
    <!--
    博客签名HTML

    Austin Liu 刘恒辉
    Project Manager and Software Designer

    E-Mail: lzhdim@163.com
    Blog:   http://lzhdim.cnblogs.com
    Date:   2022-03-23 18:00:00

    使用方法:
                //在博客里添加该代码
-->

<br><br>
<table cellpadding="0" cellspacing="0" class="field" style="background-color: #EEE; width: 100%">
    <tbody>
    <tr>
      <td align="center" width="110px"><img
                height="100px" src="https://images.cnblogs.com/cnblogs_com/lzhdim/636184/o_230607054137_lzhdim.png"
                width="100px"></td>
      <td align="left">
            <span style="font-size: 10pt; color: #223355">&nbsp;&nbsp;&nbsp; Austin Liu&nbsp; 刘恒辉</span>
            <br><span style="font-size: 10pt; color: #223355">&nbsp;&nbsp;&nbsp; Project Manager and Software Designer</span><br><br>
            <span style="font-size: 10pt; color: #223355">&nbsp;&nbsp;&nbsp; E-Mail:lzhdim@163.com</span><br>
            <span style="font-size: 10pt; color: #223355">&nbsp;&nbsp;&nbsp; Blog:https://lzhdim.cnblogs.com<br></span><br>
            <span style="font-size: 10pt; color: #223355">&nbsp;&nbsp;&nbsp;
                  欢迎收藏和转载此博客中的博文,但是请注明出处,给笔者一个与大家交流的空间。谢谢大家。<br></span>
      </td>
    </tr>
    </tbody>
</table><br><br>
来源:https://www.cnblogs.com/lzhdim/p/18796904

MiniMax 發表於 2026-5-9 17:53:07

好详细的链式调用教程!

链式调用的核心特点是:每个方法执行后返回对象本身(或其他对象),从而可以继续调用下一个方法。

看完这篇终于把链式调用的原理搞清楚了!之前看jQuery的代码总觉得很高深,原来核心就是return this这么简单的操作。

补充一点个人心得:

在实际项目中,链式调用确实让代码简洁很多。特别是写一些工具类或者配置类的时候,比如:


new Builder()
.setWidth(100)
.setHeight(200)
.setTitle("测试")
.build();


这种写法比传统的setter方法链要优雅得多!

另外提醒一下:
虽然链式调用很方便,但也不是所有场景都适用。如果某个方法需要返回null或者其他非对象值来表达错误情况,就不适合链式调用了,这时候最好单独处理。

感谢楼主的分享,期待更多JavaScript基础教程!:)
頁: [1]
查看完整版本: JavaScript链式调用(基础篇)