gpt4 book ai didi

javascript - 使用 ".delay"启用链接方法

转载 作者:行者123 更新时间:2023-11-29 10:54:21 25 4
gpt4 key购买 nike

我想知道如何实现这种方法链风格:

var foo = function(){};

foo.prototype = {
say : function(s){
alert(s);
return this;
},
delay : function(ms){
var _this = this;
setTimeout(function(){
return _this;
}, ms);
return this; // If I omit this, there will be an error.
}
}

var bar = new foo();
bar.delay(2000).say('hello'); // this will immediately alert 'hello'.

我想这样使用:

bar.delay(2000).say('hello'); // in 2 sec. say 'hello'.

不是这样的:

bar.delay(2000, function()...); // it's not a chained method

这可能吗?

最佳答案

是的,这是可能的,但您不能通过简单地在 ms 之后从 delay() 函数返回来做到这一点 - 对 setTimeout 的调用是异步的,因此会立即返回。要实现此效果,您必须实现自己的排队系统。一些代码:

var queue = new Queue();

function delay(ms) {
queue.enqueue("delay");
setTimeout(function() {
popQueue(true);
}, ms);

return this;
}

function say(s) {
queue.enqueue(function() {
alert(s);
});
popQueue();

return this;
}

function popQueue(removeDelay) {
if (removeDelay) {
if (queue.peek() == "delay") queue.dequeue();
}
while (!queue.isEmpty() && queue.peek() != "delay") {
(queue.dequeue())();
}
}

本质上,代码通过修改每个“可延迟”的函数来工作,这样它就可以将自己插入到队列中,而不是立即执行。 delay() 函数将一个字符串作为“阻塞”项插入到队列中,以防止添加到队列中的函数执行。然后,您可以使用超时在给定的毫秒数后从队列中删除该 block 。

上面的代码只是让您了解如何实现延迟,而不是一个有效的示例。显然你需要某种 Queue implementation ,或者您可以修改它以使用数组,或者您可以实现自己的 SelfExecutingQueue 对象以在入队或出队后立即自动继续执行函数(直到它命中非函数对象)而不需要您手动调用 popQueue() 等...

关于javascript - 使用 ".delay"启用链接方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3424270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com