We use cookies on this site to enhance your user experience. By clicking "OK, I Agree" or using our site, you consent to the use of cookies unless you have disabled them.
View our cookie policy to learn more.

We expect the this variable inside of that function to be whatever object we're inside of right now. In that case, it is. But in so many other cases, this is something different! Like inside handleRowClick and handleRepLogDelete:

Here's the deal: when you call a function in JavaScript, you can choose to change what this is inside of that function when you call it. That means you could have one function and 10 different people could call your function and decide to set this to 10 different things.

Now, in reality, it's not that bad. But we do need to remember one rule of thumb: whenever you have a callback function - meaning someone else is calling a function after something happens - this will have changed. We've already seen this a lot: in the click functions, inside of .each(), inside of successand even inside of $row.fadeOut():

So what isthis inside of these functions? It depends on the situation, so you need to read the docs for the success function, the fadeOut() function or the .each() function to be sure. For fadeOut(), this ends up being the DOM Element that just finished fading out. So, we can actually call $(this).remove():

Oh, and quick note: this.whatIsThis is, obviously, a function. But in JavaScript, functions are actually objects themselves! And there are a number of different methods that you can call on them, like .call(). The first argument to call() is the variable that should be used for this, followed by any arguments that should be passed to the function itself.

Refresh now and check this out! this is now our thoughtful cat, meow, dog, woof object. That is what is happening behind the scenes with your callback functions.

Now that we understand the magic behind this, how can we fix it? How can we guarantee that this is always our RepLogApp object when we're inside of it?

Leave a comment!

2017-09-21Victor Bocharsky

Hey Vesela,

Downloads are available for subscribers or course owners only - you'll see a "Download" -> "Course Code" buttons in the right top corner of every chapter page. If you're not a subscriber or owner of this course - you can look over the repository of this course which is public: https://github.com/knpunive...