怎么在JavaScript中實現鏈式調用?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
什么是鏈式調用
鏈式調用在 JavaScript 語言界很常見,如 jQuery 、 Promise 等,都是使用的鏈式調用。鏈式調用可以讓我們在進行連續操作時,寫出更簡潔的代碼。
new Promise((resolve, reject) => { resolve(); }) .then(() => { throw new Error('Something failed'); }) .then(() => { console.log('Do this whatever happened before'); }) .catch(() => { console.log('Do that'); })
逐步實現鏈式調用
假設,我們要實現一個 math 模塊,使之能夠支持鏈式調用:
const math = require('math'); const a = math.add(2, 4).minus(3).times(2); const b = math.add(2, 4).times(3).divide(2); const c = { a, b }; console.log(a.times(2) + b + 1); // 22 console.log(a.times(2) + b + 2); // 23 console.log(JSON.stringify(c)); // {"a":6,"b":9}
基本的鏈式調用
鏈式調用通常的實現方式,就是在函數調用結果返回模塊本身。那么 math 模塊的代碼大致應該是這樣子的:
export default { add(...args) { // add return this; }, minus(...args) { // minus return this; }, times(...args) { // times return this; }, divide(...args) { // divide return this; }, }
方法如何返回值
上述代碼實現了鏈式調用,但是也存在一個問題,就是無法獲取計算結果。所以我們需要對模塊進行改造,使用一個內部變量來存儲計算結果。
export default { value: NaN, add(...args) { this.value = args.reduce((pv, cv) => pv + cv, this.value || 0); return this; }, }
這樣,我們在最后一步,通過 .value 就可以拿到最終的計算結果了。
問題真的解決了嗎
上面我們看似通過一個 value 變量解決了存儲計算結果的問題,但是發生第二次鏈式調用時, value 的值因為已經有了初始值,我們會得到錯誤的計算結果!
const a = math.add(5, 6).value; // 11 const b = math.add(5, 7).value; // 23 而非 12
既然是因為 value 有了初始值,那么能不能在獲取 value 的值時重置掉呢?答案是不能,因為我們并不能確定使用者會在什么時候取值。
另外一種思路是在每次鏈式調用之前生成一個新的實例,這樣就可以確保實例之間相互獨立了。
const math = function() { if (!(this instanceof math)) return new math(); }; math.prototype.value = NaN; math.prototype.add = function(...args) { this.value = args.reduce((pv, cv) => pv + cv, this.value || 0); return this; }; const a = math().add(5, 6).value; const b = math().add(5, 7).value;
但是這樣也不能徹底解決問題,假設我們如下調用:
const m = math().add(5, 6); const c = m.add(5).value; // 16 const d = m.add(5).value; // 21 而非 16
所以,最終要解決這個問題,只能每個方法都返回一個新的實例,這樣可確保無論怎么調用,相互之間都不會被干擾到。
math.prototype.add = function(...args) { const instance = math(); instance.value = args.reduce((pv, cv) => pv + cv, this.value || 0); return instance; };
如何支持不通過 .value 對結果進行普通運算
通過改造 valueOf 方法或者 Symbol.toPrimitive 方法。其中 Symbol.toPrimitive 方法優先 valueOf 方法被調用,除非是ES環境不支持。
如何支持 JSON.stringify 序列化計算結果
通過自定義 toJSON 方法。 JSON.stringify 將值轉換為相應的JSON格式時,如果被轉換值有 toJSON 方法,則優先使用該方法返回的值。
最終的完整實現代碼
class Math { constructor(value) { let hasInitValue = true; if (value === undefined) { value = NaN; hasInitValue = false; } Object.defineProperties(this, { value: { enumerable: true, value: value, }, hasInitValue: { enumerable: false, value: hasInitValue, }, }); } add(...args) { const init = this.hasInitValue ? this.value : args.shift(); const value = args.reduce((pv, cv) => pv + cv, init); return new Math(value); } minus(...args) { const init = this.hasInitValue ? this.value : args.shift(); const value = args.reduce((pv, cv) => pv - cv, init); return new Math(value); } times(...args) { const init = this.hasInitValue ? this.value : args.shift(); const value = args.reduce((pv, cv) => pv * cv, init); return new Math(value); } divide(...args) { const init = this.hasInitValue ? this.value : args.shift(); const value = args.reduce((pv, cv) => pv / cv, init); return new Math(value); } toJSON() { return this.valueOf(); } toString() { return String(this.valueOf()); } valueOf() { return this.value; } [Symbol.toPrimitive](hint) { const value = this.value; if (hint === 'string') { return String(value); } else { return value; } } } export default new Math();
看完上述內容,你們掌握怎么在JavaScript中實現鏈式調用的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注創新互聯成都網站設計公司行業資訊頻道,感謝各位的閱讀!
另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
本文名稱:怎么在JavaScript中實現鏈式調用-創新互聯
文章位置:http://m.2m8n56k.cn/article18/csccgp.html
成都網站建設公司_創新互聯,為您提供自適應網站、域名注冊、企業網站制作、定制開發、外貿網站建設、營銷型網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:[email protected]。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯