setInterval with(this)

时间:2011-03-03 00:18:03

标签: javascript 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)

      }

1 个答案:

答案 0 :(得分:9)

在构造中使用this旨在保留thissetInterval处的含义,为在给定间隔执行的实际回调调用this。如果没有手动保存,setInterval将成为调用点var self = this this.handle = setInterval(function() { alert(self.Name); }, 5000); 时函数的所有者。

这是关于这个主题的非常好的文章

另一种可以做得更好的方法是以下

{{1}}
相关问题