Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are configuration functions that "return this" common in JavaScript?

Tags:

javascript

It seems to be a common javascript convention to configure objects with methods called one after the other, for example

toy.setColor(blue).setPrice(5).setName('Blocks').setPurchaseAction(function(customer){
   ...
}) 

and so on.

Coming from a more java based background I am used to splitting up each of those method calls into separate statements, separated by a semicolon.

It probably doesn't matter when compiled into machine level language but the practice of splitting with semicolons seems like it makes code easier to read/understand. Is there a good reason for doing it like this in javascript?

like image 721
HAL Avatar asked Mar 21 '26 02:03

HAL


1 Answers

The pattern is named "method chaining" and the main advantage of such an approach is that when no need exists to hold on to a placeholder at each step then the next method may simply be called as a continuation.

Further, this type of approach is well suited for deferred execution, and many languages use such an approach. In JavaScript you can see this being used in the new-ish promise features which favor method chaining over what some refer to as "callback hell" in JavaScript.

Overall, it is just preference as it does not offer any performance benefits to use method chaining versus iteratively calling methods. However, it does read very nicely in my opinion, and the pattern pairs very well with other similar approaches.

like image 117
Travis J Avatar answered Mar 22 '26 15:03

Travis J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!