javascript - setInterval with (this) - Stack Overflow

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

Please, someone can explain me what is the meaning of (this) at the end of the function in a 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)

      }

Please, someone can explain me what is the meaning of (this) at the end of the function in a 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)

      }
Share Improve this question asked Mar 3, 2011 at 0:18 Daniel FloresDaniel Flores 7703 gold badges12 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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 bee the owner of the function at the point setInterval was called.

Here's a very nice article on this subject

  • http://www.quirksmode/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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745446656a4628078.html

相关推荐

  • javascript - setInterval with (this) - Stack Overflow

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

    8小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信