Skip to content
Advertisement

How to make chainable function in JavaScript?

Lets imagine function like this:

JavaScript

Usage of it would be like:

JavaScript

I’m looking for a way to create function that’s chainable with other functions.

Imagine usage:

JavaScript

How would I do this?

Advertisement

Answer

Sure, the trick is to return the object once you’re done modifying it:

JavaScript

http://jsfiddle.net/Xeon06/vyFek/

To make the method available on String, I’m modifying it’s prototype. Be careful not to do this on Object though, as it can cause problems when enumerating over their properties.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement