开发者

setInterval with (this)

开发者 https://www.devze.com 2023-02-14 06:43 出处:网络
Please, someone can explain me what is the meaning of (this) at the end of the function in a setInterval :

Please, someone can explain me what is the meaning of (this) at the end of the function in a setInterval :

function Klass(name) {
   开发者_StackOverflow   this.name = name;
      this.handle = null;

      this.startTimer = function() {

        this.handle = setInterval(function(obj) {

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

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

      }


The use of this in the construct is intended to preserve the meaning of this at the point setInterval is called for the actual call back that is executed at the given interval. Without the manual preservation this would become the owner of the function at the point setInterval was called.

Here's a very nice article on this subject

  • http://www.quirksmode.org/js/this.html

Another way this could be done which may be a bit clearer is the following

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号