var Calc = function (value) { /* for more security */ var me = this; /* chaning function to add */ this.add = function(x) { value += x; return me; } /* chaining function to multiply */ this.multiply = function(x) { value *= x; return me; } /* chaining function to subtract */ this.subtract = function(x) { value -= x; return me; } /* chaning function to divide */ this.divide = function(x) { value /= x; return me; } /* chaining function to give the result */ this.equals = function(callback) { callback(value); return me; } /* nomal function to return the result and to finish the chanin. */ this.end = function() { return value; } } /* How to use the calculator */ var calc = new Calc(10) .add(20) .multiply(4) .equals(function (result) { console.log("= " + result); }) .add(1).equals(function(result) { console.log(result); }).divide(3); console.log("final result: " + calc.end());
Chained Calculator in JavaScript
This is a very small yet complete example of a chain design pattern implementation in JavaScript. Please feel free to ask questions if the comments are not that descriptive.
Subscribe to:
Post Comments (Atom)
I read that Post and got it fine and informative.
ReplyDeletecalculator
Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates. tip calculator
ReplyDelete