简体   繁体   English

如何使用原型,IIFE,currying或使用new关键字在JavaScript中创建自定义可链接延迟函数

[英]How to create a custom chainable delay function in JavaScript using prototype, IIFE, currying or using new keyword

How can I create a custom chainable delay function in JavaScript using prototype or currying or using new keyword? 如何使用原型或currying或使用new关键字在JavaScript中创建自定义可链接延迟函数?

Original question is 原来的问题是

var foo = function () {
    console.log("bingo!");
};

function bar() {
    console.log("Wow!");
}
// make below two lines work
foo.delay(300); // after 0.3s: "bingo!"
bar.delay(600); // after 0.6s: "Wow!"
// This returns undefined, how to fix it?

My attempt so far. 到目前为止我的尝试。

function delay(time) {
    setTimeout(this, time);
}

var foo = (function () {
    console.log();
    console.log("bingo!");
    return {
      delay: delay.bind(this)
    }
})();

function bar() {
     console.log("Wow!");
    return {
      delay: delay.bind(this)
    }
};

// bar.prototype.delay = function() { return console.log("bar.prototype.delay"); }
foo.delay(300); // after 0.3s: "bingo!"
bar.delay(600); // after 0.6s: "Wow!"

Lastly, can I ask you where would be a good place to study these kind of topics to be more fluent in JavaScript? 最后,请问您在哪里可以学习这类主题,使他们更熟练地使用JavaScript? Thank you in advance. 先感谢您。

You have a problem with this code: 您对此代码有疑问:

setTimeout(this, time); // The first param must be the function to be executed after `n` ms.

Here you need to pass the time value to the function delay , you could pass the implicit arguments array. 在这里,您需要将time值传递给函数delay ,您可以传递隐式arguments数组。

return {
  delay: delay.bind(this) // Here you need to pass the `time` value.
}

This is an approach to bind the delay function. 这是绑定delay功能的一种方法。

return {
    delay: delay.bind(this, function() {
        console.log("Wow!");
    }, ...arguments)
}

Important: You don't to bind the function delay to pass the context this value. 重要提示:请勿绑定函数delay来传递上下文this值。 That binding it's necessary if the function delay will use the context this . 如果函数delay将使用上下文this则该绑定是必要的。

 function delay(fn, time) { setTimeout(fn, time); } var foo = (function() { return { delay: delay.bind(this, function() { console.log("bingo!"); }, ...arguments) }; })(); var bar = (function() { return { delay: delay.bind(this, function() { console.log("Wow!"); }, ...arguments) }; })(); // bar.prototype.delay = function() { return console.log("bar.prototype.delay"); } foo.delay(300); // after 0.3s: "bingo!" bar.delay(600); // after 0.6s: "Wow!" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM