Last active
October 27, 2015 03:35
-
-
Save rnaffer/763c7b44fc433dc9cc3a to your computer and use it in GitHub Desktop.
Ejemplo del patrón de diseño "Chaining" con explicación.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Util para crear API's que trabajen con objetos mutables. | |
| // Trabaja con un objeto raiz. | |
| // Patrón utilizado en JQuery y LinQ | |
| // Las funciones retornan su objeto raiz para que sea posible encadenar funciones | |
| // y hacen las operaciones sobre una variable que pertenece al objeto raiz. | |
| var Calc = function( start ) { | |
| this.add = function( x ) { | |
| start = start + x; | |
| return this; | |
| }; | |
| this.multiply = function( x ) { | |
| start = start * x; | |
| return this; | |
| }; | |
| this.equals = function( callback ) { | |
| callback(start); | |
| return this; | |
| }; | |
| } | |
| // Ejemplo final | |
| new Calc( 0 ) | |
| .add( 1 ) | |
| .add( 2 ) | |
| .multiply( 3 ) | |
| .equals(function( results ) { | |
| console.log( results ); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment