多次调用同一异步方法体会出现使用相同的属性值问题

《一》执行同一个方法体,里面有异步的逻辑代码,如果这个异步请求还没有执行完毕时,我们又对它进行了第二次调用,它会使用最后一次的执行操作。例如:

var test = {

init:function(){

this.temp = "temp" + new Date().getTime();

console.log(this.temp );

self = this;

this[this.temp] = function(){

setTimeout(function(){

console.log(this.temp);

},3000)

                }

},

excute:function(){

this[this.temp]();

}

};

第一次执行:

test.init();

test.excute();

 第二次执行:

test.init();

test.excute();

在两次init时输出的 temp是各不相同 。

但我们在异步函数体输出的却是相同的,也即是第二次执行的被第一次的给覆盖掉了 。这和我们理想中的状态差别不是一般的大。在很多应用场景当中,比如说我们做了一个异步请求,还没有来得异步数据处理完毕,我们又进行了第二次操作。 就会出现处理数据混乱。

《二》有没有解决办法呢:请看下面的代码:

var test = {

init:function(){

this.temp = "temp" + new Date().getTime();

console.log(this.temp);

self = this;

this[this.temp] = (function(){

var bb = self.temp;

return function(){

setTimeout(function(){

console.log(bb);

},3000)

}

})();

},

excute:function(){

this[this.temp]();

}

};

test.init();

test.excute();

这个也就是在异步包含体给加了一个闭包,把所要传的值放在临时变量中,这样就解决了重复调用最后的属性值了。

猜你喜欢

转载自blog.csdn.net/weixin_41148727/article/details/82857615