Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

4 different scenarios of 'this'. What's the correct interpretation?

Tags:

jquery

this

call

These are taken from the tuts-premium Jquery vid tutorials.
http://tutsplus.com/lesson/the-this-keyword/ Jeff explains what 'this' is referring to each time but I'm not sure I've grasped the reasoning behind them all.

E.g. 1

function doSomething(e) { 
e.preventDefault(); 
console.log(this);
} 

$('a').on('click', doSomething);

In this case "this refers to the 'a' element" (being in this case the parent object)

I guess that's because here the statement equates to :

$('a').on('click', function (e) { 
    e.preventDefault(); 
    console.log(this);
    } 

So 'a' is the parent object

E.g. 2

var obj = { 
    doIt: function(e){ 
    e.preventDefault(); 
    console.log(this);
    }
}

$('a').on('click',  obj.doIt);

In this case "this still refers to the 'a' element " (*but apparently it's not the parent object?)

It seems this time we're calling a method but the statement still equates to the same thing as E.g. 1

*One thing in the tutorial has me a bit confused. I thought 'this' always refers to the parent object so in this case 'a' is still the parent object. But (at 05.23 in the tutorial ) he infers that's not the case, stating "there may be times when you want 'this' to refer to it's parent object which would be 'obj' " in which event he creates e.g.3.

E.g. 3

var obj = { 
    doIt: function(){ 
    console.log(this);
    }
}

$('a').on('click',  function(e){    
obj.doIt(); 
        };
e.preventDefault(); 

In this case "this refers to the obj object"

I presume this to with the fact that 'this' is in a nested function as this statement equates to :

$('a').on('click',  function(){    
function(){ console.log(this);}
};
e.preventDefault(); 

I don't really understand why though, particularly as I read in an article that in nested functions 'this' "loses its way and refers to the head object (window object)".

E.g.4

var obj = { 
    doIt: function(){ 
    console.log(this);     
    }
}

$('a').on('click',  function(e){    
       obj.doIt.call(this);             
       e.preventDefault(); 
});

In this case "This refers to the 'a'"

According to Javascript Definitive Guide "The first argument to both call() is the object on which the function is to be invoked" Here "this" is the used as the first argument. But "this" is not the object on which the function is to be invoked??
I think I get that the call function is there to invoke the function and use its first parameter as a pointer to a different object but I don't get why using 'this' means the function is invoked by 'a'. It's not something I've seen in other call() examples either.

Sorry for such a mammoth post. Hopefully someone's still reading by this stage…

like image 716
fivedoor Avatar asked Apr 12 '12 00:04

fivedoor


People also ask

What are the different types of scenarios?

There are generally four types of scenarios: exploratory scenarios, target-seeking scenarios, policy- screening scenarios, and retrospective policy evaluation ( Figure 3). These different types of scenarios generally contribute to different decision-making contexts. ...

What are scenarios and examples?

The definition of a scenario is a series of events that is projected to occur. When you run through all of the possible outcomes of a conversation in your head, this is an example of a situation where you run through all possible scenarios. noun.

What is scenario situation?

So a situation is a singular location / combination of properties at a point in time whereas a scenario is a series of events that follow logically within a causal frame of reference (like a scene in a play - connected but distinct events).

What is scenario description?

A scenario is a story or story outline. Thinking about the future normally involves creating alternative scenarios, or stories, about the possible evolution of drivers.


1 Answers

I hope this helps clarifying the issue, it can be confusing indeed.

  • When this is loose on your code, it will refer to the global object (in web browsers, that is window).

    console.log(this); // window
    
  • When this is inside an object method (like on your E.g. 3), it will refer to the object. This aplies to objects instanced with new, or as object literals (like on your example).

     var obj = { 
         doIt: function(e){ 
             console.log(this);
         }
     }
     obj.doIt(); // obj
    
  • Inside an event handler, this will refer to the object the event is bound to.

    // This is the plain js equivalent of your jQuery example
    document.getElementsByTagName['a'][0].addEventListener('click', function(e){
        console.log(this); // the first anchor on the document
    });
    
    // This is exactly the same:
    var clickHandler = function(e){
        console.log(this); // the first anchor on the document
    };
    document.getElementsByTagName['a'][0].addEventListener('click', clickHandler); 
    
    // Even if the handler is defined inside of another object, this will be
    // the obj the event is bound to. It's the case of your E.g. 2
    var obj = { 
        doIt: function(e){  
            console.log(this); // the first anchor on the document
        }
    }
    document.getElementsByTagName['a'][0].addEventListener('click', obj.doIt);
    // When you pass obj.doIt to addEventListener above, you are passing a reference
    // to that function. It's like "stealing" the function from the object
    
  • When an object is passed as the first parameter to Function.call or Function.apply, if this appears inside of the function it will refer to the object you passed. It's a way to force what this will be pointing to.

    var obj = { 
        doIt: function(){ 
            console.log(this); // window 
        }
    }
    obj.doIt.call(window);
    
like image 79
bfavaretto Avatar answered Oct 21 '22 20:10

bfavaretto