简体   繁体   中英

JavaScript: Executing chained methods in any order

Suppose I have a function called log which simply prints the given string.

Can I refactor my code so both of these function could work?

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

You can do something similar with nested class logics:

 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()); 

If you are comfortable with promises, then you can do something like this:

 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"); 

This removes the need for a .print call.

我做了一个图书馆来解决这个问题https://github.com/omidh28/clarifyjs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM