This inside callback is defined as form element

In chapter 9, we learn that this inside a callback is not assigned to an object. But in addSubmitHandler, we have

this.$formElement.on('submit', function (event) {
  event.preventDefault();

  var data = $(this).serializeArray();
  console.log(data);
});

and in this case this (the jQuery wrapped one) refers to the form element. Isn’t this inside a callback? If so, why is this defined to be the form element? I am guessing it is because somehow the on method assigns this to the calling object. Is that it?

Hi @ballgeier! Sorry for the delay, you probably figured this out, but just in case:

Since all functions are the same in JS (e.g. there aren’t special “kinds” of functions), the only difference is how you call the function.

Callbacks are usually invoked like this: myCallback(), while “methods” are invoked this way: myObj.myCallback(). Depending on which way you invoke a function, its value for this will change.

jQuery invokes your callback function yet another way: with myCallback.apply. With this version, jQuery can invoke your callback and specify a value for this. So jQuery chooses to change the value of this in your callback to the DOM element: myCallback.apply(event.currentTarget).

If you wanted, you could do something similar in your own code, but we chose to invoke callback functions with cb() instead of cb.apply(valueForThis) since we didn’t really need to use this.

Hope that helps!