在JavaScript中创建队列并在匿名函数中访问全局变量
我不太精通JavaScript。我在下面有一个对象(Foo.bar),我希望每100毫秒从队列中馈送和打印项目在JavaScript中创建队列并在匿名函数中访问全局变量,javascript,Javascript,我不太精通JavaScript。我在下面有一个对象(Foo.bar),我希望每100毫秒从队列中馈送和打印项目 var Foo = Foo || {}; Foo.bar = { initialize: function () { this.feedQueue(); this.consumeQueue(); }, queue: [], consumeQueue: function () { if (this.queue
var Foo = Foo || {};
Foo.bar = {
initialize: function () {
this.feedQueue();
this.consumeQueue();
},
queue: [],
consumeQueue: function () {
if (this.queue > 0) {
var item = this.queue.shift();
console.log(item);
}
setTimeout(function () {
this.consumeQueue();
}, 100);
},
feedQueue: function () {
this.queue.push(Math.random());
setTimeout(function () {
this.feedQueue();
}, 100);
}
};
Foo.bar.initialize();
在ConsumerQueue函数中,“this.queue”从不更新。它总是空的
有人能帮我解决我做错了什么吗?您需要定义超时函数的作用域,否则此
具有不同的上下文
setTimeout((function () {
this.consumeQueue();
}).bind(this), 100);
在回调函数
中,此
等于窗口
,因为调用回调函数时会忽略此
正如他在回答中所说,你可以像这样使用bind
setTimeout((function () {
this.consumeQueue();
}).bind(this), 100);
或您可以将此
作为参数传递给callack函数
setTimeout(function (context) {
context.consumeQueue();
}, 100, this);
在这两种情况下,如果您使用IE作为浏览器,您至少需要IE9。为什么绑定,为什么参数
setTimeout((function () {
Foo.bar.consumeQueue();
}), 100);
作为绑定或将其传递给回调函数的最后一种替代方法,这应该在IE9之前起作用:
...
consumeQueue: function () {
if (this.queue > 0) {
var item = this.queue.shift();
console.log(item);
}
var that = this;
setTimeout(function () {
that.consumeQueue();
}, 100);
},
...
经典超时具有不同的上下文(
this
)问题setTimeout(this.consumerqueue.bind(this),100)
为什么要向下投票?是的,它应该是Foo.bar
,而不仅仅是Foo
。但它是一个(+1)Aaaaa。。对我不专心。但是使用call或arguments有什么好处呢?@Deep通过使用bind或arguments,你不会创建一个闭包,这是我能看到的唯一一点,但你的答案值得我投票。也许吧。我认为TS只有一个队列实例。我认为调用和参数会创建递归指针。这可能会导致IE上的memleak。在这方面,我不确定是否有必要知道