Javascript conflict with 'this' reference

This question already has an answer here:

I have a piece of javascript code (using jQuery) that says:

$('.duration').each(function() {
    $(this).html(this.duration_text);
});

It's iterating over each element of class 'duration' and setting the text as needed. The problem, is that the text it is setting is from a member variable, hence the this.duration_text. The 'this' reference is getting clobbered by the 'this' reference used by jQuery in the iteration.

How can I avoid this collision?

Although the underlying concept of the answer may be the exact same as the question this is marked as a duplicate of, it isn't immediately clear to me that this is the same question. In hindsight, sure, but while searching myself I didn't find it, nor was it clear it was the same question if I did find it.

Answers 1

  • You can use a closure variable to hold the reference to the outer object

    var self = this;
    $('.duration').each(function() {
      $(this).html(self.duration_text);
    });
    

    But in the given snippet since you are assigning the same content to all duration elements, you can just use

    $('.duration').html(this.duration_text);
    

Related Articles