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

时间:2017-04-24 11:24:12

标签: javascript

假设我有一个名为log的函数,它只打印给定的字符串。

我可以重构我的代码,这样这两个功能都可以吗?

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

1 个答案:

答案 0 :(得分:2)

您可以使用嵌套类逻辑执行类似的操作:

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电话的需要。