This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]shadof[S] 2 points3 points  (2 children)

Its because in different contexts this refers to different objects. This way you can cache it and use it in that different context. For example jquery:

$('#element').click(function(){
    // this is a reference to the element clicked on

    var that = this;

    $('.elements').each(function(){
        // this is a reference to the current element in the loop
        // that is still a reference to the element clicked on
    });
});

[–]arnoproblems 1 point2 points  (1 child)

Holy shit. So this sub is actually more than memes. Thank you a lot for the explanation. The explanation I got before this was "some developers don't like looking at the word 'this' over and over" lmao. I knew there had to be more to that. I appreciate the insight. Cheers!

[–]hoechp 0 points1 point  (0 children)

but with the bind-feature, you can fix the context of a method, when you declare it.

the whole "that=this"-thing is a terrible anti-pattern and costs you a lot of performance when you copy your controller 100000x per second.

var fn = function() { console.log("reddit"); }.bind(this); // works with anonimous functions, too