nodeJs中过期的键

时间:2017-03-30 05:06:58

标签: javascript node.js express

我想为键值存储创建一些模式,结构如下:

function ItemObject(value1, value2, value3) {
    this.value1 = value1;
    this.value2 = value2;
    this.value3 = value3;
    // or whatever object needs.
}

然后,我做了一个类似的函数:

function keystore() {
    this.keys = new Array();
    this.decaytime = 50000; //in second
}

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys[key] = itemObject;
    setTimeout(this.removeKey(key), this.decaytime);
}

keystore.prototype.removeKey = function(key) {
    console.log('removing ' + key);
    console.log(this.keys);
    if (this.keys[key]) {
        delete this.keys[key]
    }
    console.log('done');
    console.log(this.keys);
}


module.exports = keystore;

现在,我想在this.keys[keyid]之后删除decaytime。我怎样才能做到这一点?因为this.removeKey()setTimeout()范围之外,显然不是函数,因为它尚未在setTimeout中声明。我需要removeKey()作为对象的一部分,因为我想在需要时提前删除密钥,所以我会保留removeKey()

谢谢

编辑:我找到了一种方法,但它很难看。

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys[key] = itemObject);
    var _this = this;
    setTimeout(function() {_this.removeKey(key);}, this.decaytime);
}

有没有正确的方法?

1 个答案:

答案 0 :(得分:1)

对setTimeout使用箭头函数,将保留this上下文。

function keystore() {
    this.keys = new Array();
    this.decaytime = 2000; //in second
}

keystore.prototype.storeKey = function(key, itemObject) {
    this.keys.push(key, itemObject);
    setTimeout(() => this.removeKey(key), this.decaytime);
}

keystore.prototype.removeKey = function(key) {
    console.log('removing ' + key);
    console.log(this.keys);
    if (this.keys[key] != null) {
        this.keys = this.keys.filter((item, index) => index !== key);
    }
    console.log('done');
    console.log(this.keys);
}