0

So I've been trying to learn what 'this' points to under different circumstances. From what I have learned, it depends on the site-call of a function and the following:

If the function is called on its own, the 'this' keyword will point to the global object.

If the function is called as a property of an object (as a method), the 'this' keyword will point to the parent object.

If a function is used as a function constructor, 'this' will point to the newly created empty object.

Then you have call, apply, bind, where you can decide which object 'this' points to.

However, for the code below, I am a little confused.

$("ul").on("click", "span", function(event){
    $(this).parent().fadeOut(500,function(){
        $(this).remove();
    });
    event.stopPropagation();
});

Please correct me where I go wrong:

  1. 'On' function is called and new execution context is created, 'this' is pointing towards new object created by $ function constructor.

  2. 'On' remains on the execution stack and the passed in a function gets called gets popped on the execution stack, and a new execution context is created.

  3. 'this' for the new execution context for the passed in 'callback' function, points to the 'span' object. Why?

The site-call for the callback function is within the 'on' function and is simply invoked as 'callback();', shouldn't the 'this' keyword, in this case, be pointing to the global object?

  1. I can ask the same question for the inner 'this' also for the timeout function, which is pointing to span's parent which in my HTML is a 'li'.

How are the 'this' keywords pointing to these objects and not the global object?

Have I misunderstood something about 'this' in vanilla javascript, or is there some magic happening in jQuery?

Many thanks for your time and patience, Mark

  • 1
    jQuery magic is happening - internally it uses `call` or `apply` to ensure that `this` refers to the element of interest. – Alnitak May 29 '18 at 09:31
  • I'm not sure you are correct in all your first assumptions, but to be a little more precise for your case, in jQuery's selection and event callback functions, `this` always refer to the selected or target object – Kaddath May 29 '18 at 09:34
  • `this` or `$(this)` generally refer to the "execution context", within the "current scope" ... https://hackernoon.com/execution-context-in-javascript-319dd72e8e2c – Martin Zeitler May 29 '18 at 09:41
  • See [this](https://stackoverflow.com/questions/7479282/this-vs-this) or [this](https://stackoverflow.com/questions/1051782/jquery-whats-the-difference-between-this-and-this) question on SO. – Hinrich May 29 '18 at 11:25
  • Great, thanks all! – Mark Cosgrave May 30 '18 at 07:35

0 Answers0