简体   繁体   English

setInterval with(this)

[英]setInterval with (this)

Please, someone can explain me what is the meaning of (this) at the end of the function in a setInterval : 请有人在setInterval函数的末尾解释一下(this)的含义是什么:

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)

      }

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. 在构造中使用this旨在保留this的含义。在给定间隔执行的实际回调中调用setInterval Without the manual preservation this would become the owner of the function at the point setInterval was called. 如果没有手动保存, this将成为调用setInterval时函数的所有者。

Here's a very nice article on this subject 这是一篇关于这个主题的非常好的文章

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM