SetInterval with (this)

Please can someone explain to me what (this) means at the end of a function in setInterval:

function Klass(name) {
      this.name = name;
      this.handle = null;

      this.startTimer = function() {

        this.handle = setInterval(function(obj) {

          return(function() {
            alert(obj.name);
            });

          }(this), 5000); // <-------------------- (this)

      }
+3
source share
1 answer

Use thisin the design is intended to store the value thisat the point setIntervalfor the actual callback performed at a given interval. Without saving manually this, I would become the owner of the function at the point setInterval.

Here is a very good article on this subject.

Another way that can be done, maybe a little clearer, is the following

var self = this
this.handle = setInterval(function() { alert(self.Name); }, 5000);
+9
source

Source: https://habr.com/ru/post/1795901/


All Articles