Javascript setInterval作用域问题 [英] Javascript setInterval scoping issue

查看:88
本文介绍了Javascript setInterval作用域问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我试图用来管理客户端会话的类,它看起来像这样:

I have a class I am attempting to use to manage a session on the client side, it looks like this:

var sessionmanager;

sessionmanager = (function() {

  sessionmanager.name = 'sessionmanager';

  function sessionmanager(timeout, action) {
    if (action != null) {
      this.action = action;
    } else {
      this.action = null;
    }
    if (timeout != null) {
      this.timeout = timeout * 60;
    } else {
      this.timeout = 0;
    }
  }

  sessionmanager.prototype.run = function() {
    return window.setInterval(this.tick, 1000);
  };

  sessionmanager.prototype.sessionExpired = function() {
    if (this.action != null) {
      window.navigate("timeout.asp");
    }
  };

  sessionmanager.prototype.setTimeout = function(timeout) {
    return this.timeout = timeout;
  };

  sessionmanager.prototype.tick = function() {
    this.timeout -= 1;
    if (this.timeout < 1) {
      return sessionExpired();
    }
  };

  return sessionmanager;

})();

但是当我在 tick 函数内调试时从 setInterval 回调中调用我得到 this.timeout = NaN

However when I debug inside the tick function that is called from within the setInterval callback I get this.timeout = NaN

我猜我错误的做了什么?请帮忙?我是新来的javascript ...

I am guessing I scoped something incorrectly? Help please? I am new to javascript...

推荐答案

如果 setInterval 调用函数它没有像你期望的那样设置这个值。调用 this.tick() 正确设置它,但只是传递函数并以另一种方式调用它不会。您必须将值绑定到您想要的值:

If setInterval calls the function it doesn't set the this value as you may expect. Calling this.tick() does set it correctly, but just passing the function and having it called in another way does not. You have to bind the this value to what you want:

setInterval(this.tick.bind(this), 1000);

这适用于较新的浏览器,但有可用垫片。

This is available on newer browsers but there are shims available.

另外,你可能意味着 this.sessionExpired(),就像它定义的那样。 return 没有多大意义,因为 setInterval 并不关心返回值。

Also, you probably meant this.sessionExpired(), as that's where it's defined. return doesn't make much sense there since setInterval does not care about the return value.

这篇关于Javascript setInterval作用域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆