Last active
August 7, 2022 18:37
-
-
Save cmcdevitt/26558243557b8bbf44f124eeef39ee39 to your computer and use it in GitHub Desktop.
JavaScript Chaining How To
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
| 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