簡體   English   中英

JavaScript:以任何順序執行鏈接方法

[英]JavaScript: Executing chained methods in any order

假設我有一個叫做log的函數,它只打印給定的字符串。

我可以重構代碼,以便這兩個功能都能正常工作嗎?

log("needsChange").doSomethingWithTheStringBeforePrintingIt();
log("perfectStringToPrint");

您可以使用嵌套類邏輯執行類似的操作:

 var log = (function() { //Class var _log = (function() { function _log(message) { this.message = message; } _log.prototype.doSomethingWithTheStringBeforePrintingIt = function() { this.message = this.message.split("").reverse().join(""); return this; }; _log.prototype.capitalizeFirstWord = function() { this.message = this.message[0].toUpperCase() + this.message.substr(1); return this; }; _log.prototype.print = function() { return this.message; }; return _log; }()); //Instancer function return function log(message) { //Return instance of class return new _log(message); }; })(); //Test console.log(log("needsChange") .doSomethingWithTheStringBeforePrintingIt() .capitalizeFirstWord() .print(), log("perfectStringToPrint") .print()); 

如果您對諾言感到滿意,則可以執行以下操作:

 var logger = (function() { //Class var _log = (function() { function _log(message) { var _this = this; this.message = message; this.promise = null; this.promises = []; this.promise = Promise.all(this.promises).then(function(values) { console.log(_this.message); // [3, 1337, "foo"] }); } _log.prototype.reverse = function() { var self = this; this.promises.push(new Promise(function(resolve, reject) { setTimeout(resolve, 0, (function() { self.message = self.message.split("").reverse().join(""); })()); })); return this; }; _log.prototype.capitalizeFirst = function() { var self = this; this.promises.push(new Promise(function(resolve, reject) { setTimeout(resolve, 0, (function() { self.message = self.message[0].toUpperCase() + self.message.substr(1); })()); })); return this; }; return _log; }()); //Instancer function return function log(message) { //Return instance of class return new _log(message); }; })(); //Test logger("needsChange").reverse().capitalizeFirst().reverse(); //Capitalizes last letter logger("perfectStringToPrint"); 

這消除了對.print調用的需要。

我做了一個圖書館來解決這個問題https://github.com/omidh28/clarifyjs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM