From the course: JavaScript: Best Practices for Functions and Classes

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Return this from methods

Return this from methods - JavaScript Tutorial

From the course: JavaScript: Best Practices for Functions and Classes

Start my 1-month free trial

Return this from methods

- [Instructor] Methods organized within a class provide a toolbox for use with class instances. In the code for this video, the cart class includes three methods which calculate tax, shipping and the grand total for cart contents. At the bottom of the file, I've written test code to call all three of these methods in order, and then check the result. I'm going to run that code in my browser console, and I can see that the result is an object that contains tax, shipping, and grand total properties. I can enhance my methods for this class by returning this from each one. The advantage to adding this to my code is that I can chain methods together because each method passes the result to the next method. And that lets me write more compact code that's easier to understand. Organizing code in this way creates what's known as a fluent interface. In the calcTax method, I simply add return this to the end. And likewise…

Contents