Skip to content

Instantly share code, notes, and snippets.

@rnaffer
Last active October 27, 2015 03:35
Show Gist options
  • Select an option

  • Save rnaffer/763c7b44fc433dc9cc3a to your computer and use it in GitHub Desktop.

Select an option

Save rnaffer/763c7b44fc433dc9cc3a to your computer and use it in GitHub Desktop.
Ejemplo del patrón de diseño "Chaining" con explicación.
// 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