Thursday, 23 February 2012

WTF is THIS

Simply do a console.log(this). You will see that this refers to the parent or the window object.

Lets try it inside a self invoking function, like this:
(function doSomething(){
   console.log(this);
})();


Again it gives the window object

Now lets try to run the function when an anchor tag is clicked
<a href="http://www.google.ca">click</a>

$('a',on('click',doSomething)); 
Now you will see that this will refer to the anchor tag.

Suppose if we put the functin as a method inside an object like this:
var obj = {
        init : function(e){
                e.preventDefault();
                console.log(this);
            }
    };

    $('a').on('click',obj.init);
Now also, this will refer to the anchor tag. But if we do like this,
    var obj = {
        init : function(){
                    console.log(this);
            }
    };

    $('a').on('click',function(e){
        obj.init();
            e.preventDefault();
    });
This will refer to the object now.

How to specify what this this refers to:

This can be dcne using the call or apply methods
    $('a').on('click',function(e){
        obj.init.call(this);
            e.preventDefault();
    });
Now, this will refer to the anchor tag instead of the object. You can also pass the

event object like so, obj.init.call(this,e);

You can also use jQuery's $.proxy method to set the value for this manually,
$('a',on('click',$.proxy(obj.init, obj))
If we do like this, this will refer to obj within the function

No comments:

Post a Comment