In the examples folder, open up the context sub folder and took a look at the file named method chaining. And here I've got the entire application, but I've changed the code dramatically. Whereas earlier, we just had kind of jQuery code just laid out in a more procedural manner. Here, I have created an object called app. And then I've created different methods called init. And start and Dom setup, and etc.
So the code is much more object oriented. It's a little bit cleaner, easier to read and easier to manage. But I've done something down here that it's a pattern that I want to just discuss for a couple of minutes. I'm doing something called method chaining. So I'm calling the DOM setup method, the bind reload page event handler method, the bind delete selected event handler method and the bind user items event handlers method. But in each case, I'm not saying app dot that method like you would expect I'm just saying app dot app dot DOM, setup dot binary loadable blah, dot bind believable dot bind.
So I'm calling app, but then I'm just calling different methods on app. So how is it that I can skip using App dot app dot app dot every time? Well, let's take a look at each one of these methods. So let's look at the DOM setup method down here. So Dom setup has an interesting line. It does a bunch of stuff that we're not really worried about right now.
But it returns this. And if we remember what is the JavaScript, this keyword referred to refers to the object to which a method belongs. And the DOM setup method belongs to the app object. So this method returns this or returns app. So when I execute this code here in line number 21, here, I wind up with app, so I could just turn around and call the Bynes reload page of an answer. method.
And then when that method executes bind reload page event handler, I returned this. So since executing that function returns app, I can turn around and called bind, delete selected event handler, and so forth. So if each method returns the app object, that means I can turn around and call another method on that object. This is called method chaining. And it doesn't effectively change your code in terms of what your code does. But it allows you to write code that's maybe easier to read, and a little bit more expressive.
Because if I, someone else wrote this code, and I inherited it, the first thing I would say is, oh, this app method has a number of this app object has a number of methods, and I'm calling them all here. And all these methods return the app object, that's for sure. There's no doubt in my mind, because I know that you couldn't do this you couldn't method chain like this. If these methods did not return the app. object and method chaining is really easy. It just you just need to return the object to which that method belongs from each one of the methods, allowing you to chain methods off of a single reference to an object.