Skip to content

Instantly share code, notes, and snippets.

@cmcdevitt
Last active August 7, 2022 18:37
Show Gist options
  • Select an option

  • Save cmcdevitt/26558243557b8bbf44f124eeef39ee39 to your computer and use it in GitHub Desktop.

Select an option

Save cmcdevitt/26558243557b8bbf44f124eeef39ee39 to your computer and use it in GitHub Desktop.
JavaScript Chaining How To
var ChainIt = Class.create();
ChainIt.prototype = {
initialize: function() {
//Persistence varables go here.... maybe an object
this.answer = '';
},
addAnswer: function(add_it){
//add_it = string
this.answer = add_it;
return this; //Each function needs to return "this" for the next item in the chain
},
getAnswer: function(){
return this.answer;//In theory the final item in the chain
},
doubleAnswer: function(){
this.answer = this.answer + " " + this.answer;
return this;
},
printAnswer: function(){
gs.info("CCCC " + this.answer);
return this;
},
type: 'ChainIt'
};
/*
Examples
var chain = new ChainIt().addAnswer("Foo Bar").doubleAnswer().printAnswer().getAnswer();
var chain = new ChainIt();
var out = chain.addAnswer("foo bar").doubleAnswer().printAnswer().getAnswer();
gs.info(out);
Source:
https://blog.segunolalive.com/posts/understanding-method-chaining-in-javascript/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment