用Nodejs创建临时对象

Create temporary object in Nodejs

本文关键字:临时对象 创建 Nodejs      更新时间:2023-09-26

是否可以创建临时对象?

对象将在10秒内自动取消设置

也许我想用这样的东西

var foo = {};
foo[username] = 0;
setTimeout(function () { delete foo[username]; }, 10000);
如果在1000多个对象上使用

,上面的代码对服务器不好吗?

或者谁有更好的主意?

可以创建一个具有属性的对象,该属性将在指定的超时后自动将属性设置回undefined

function Foo(timeout) {
  var temp;
  var timer;
  Object.defineProperty(this, 'temp', {
    get: function () {
      return temp;
    },
    set: function (value) {
      temp = value;
      timer = setTimeout(this.reset, timeout);
    }
  });
  this.reset = function() { temp = undefined; };
}

然后使用它看起来像:

// Console:
> var foo = new Foo(10000); // specifies how long to timeout in ms
> foo.temp // undefined
> foo.temp = 5;
> foo.temp // 5
> // 10 seconds ellapse
> foo.temp // undefined

你也可以做一些事情,比如当一个值存在或一个现有的计时器正在运行时阻止任何更新。这完全取决于设计需要。