2017-04-24 42 views
1

假設我有一個函數叫做log,它只是打印給定的字符串。JavaScript:以任何順序執行鏈式方法

我可以重構我的代碼,這兩個函數都可以工作嗎?

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

這句法是可能的,如果日誌返回函數DoSomething的,或與該方法的對象。 – Shilly

+0

@Shilly是的,但問題是,字符串已經打印出來,所以它要遲到做任何事情。 – omidh

+0

您必須在打印字符串之前進行所有編輯。埃米爾的回答告訴你如何做到這一點。如果你有辦法檢測一個字符串是否是'perfectStringToPrint',如果'needsChange'被檢測爲不完美,通過將實際的console.log調用移動到'doSomethingWithTheStringBeforePrintingIt'中,仍然有可能得到這個確切的語法。 – Shilly

回答

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電話的需要。