Quantcast
Channel: What is the reason for var $this = this - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by pimvdb for What is the reason for var $this = this

$
0
0

Generally, this means a copy of this. The thing about this is that it changes within each function. Storing it this way, however, keeps $this from changing whereas this does change.

jQuery heavily uses the magic this value.

Consider this code, where you might need something like you are seeing:

$.fn.doSomethingWithElements = function() {    var $this = this;    this.each(function() {        // `this` refers to each element and differs each time this function        //    is called        //        // `$this` refers to old `this`, i.e. the set of elements, and will be        //    the same each time this function is called    });};

Viewing all articles
Browse latest Browse all 7

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>