Why does 'this' refer to the jQuery object when it is called on the xxx.click event?

I am doing some linking exercise and I have a silly question about jquery click function. Why, when I pass the method to click, 'this' points to the jquery object that the click was clicked on, but when I pass the anonymous function it doesn't? I understand that if 'this' refers to a jquery object then we need to use bind, but I don't understand why 'this' changes.

var test = {
    data: 'Hello World',
    getData: function() {
        console.log(this.data);
    }    
};
//Base case - calling a method on an object
test.getData();

//test 1 -> doesn't work
$('#test1').click(test.getData);

//test2 -> works
$('#test2').click(test.getData.bind(test));

//test3 -> works
$('#test3').click(function(event) {
    test.getData();
});

      

http://jsfiddle.net/17h6h4yq/

+3


source to share


1 answer


This is because this

in the click function, this is the item that was clicked.

So this line:

$('#test1').click(test.getData);

      

Convert this

inside your function to #test1

.

This line:

$('#test2').click(test.getData.bind(test));

      



You are using bind that change this

to the first parameter sent. In this case: the object test

.

And this line:

$('#test3').click(function(event) {
    test.getData();
});

      

You have a function that triggers another function. The clicked element (mentioned in the first snippet) is passed to the first function.

$('#test3').click(function(event) {
    console.log(this); //`#test3`
    test.getData();
});

      

This means the text.getData()

this

value does not change, it is orignal. In other words, it this

will be an object test

.

+2


source







All Articles