简体   繁体   English

JavaScript:以任何顺序执行链接方法

[英]JavaScript: Executing chained methods in any order

Suppose I have a function called log which simply prints the given string. 假设我有一个叫做log的函数,它只打印给定的字符串。

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. 这消除了对.print调用的需要。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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