通过 "function_name.callAfter(ms, param1, param2, ...)" 形式的调用延迟执行任何现有函数

Delay-execute any existing function by a call of the form "function_name.callAfter(ms, param1, param2, ...)"

我最近有一道面试题,我没有答对。开始了:

Write an implementation of a function callAfter that enables ANY function to be called after some specified duration. The output of the function should remain the same. The function should have > following syntax:

Example 1: Let's say you have a function called sum like so:

function sum(a, b) {
 console.log('Sum is: ', a + b);
}

Now you should be able to execute:

sum.callAfter(5000, 8, 9);

This should invoke the function sum after 5 seconds with parameters 8 and 9. Output: 'Sum is: 17'.

Example 2: For a function difference with the following implementation:

function difference(a, b) {
  console.log('Difference is: ', a-b);
}

You should be able to execute:

difference.callAfter(4000, 8, 6);

This should invoke the function difference after 4 seconds with parameters 8 and 6. Output: 'Difference is: 2'.

注意:我知道我可以在 n 秒后执行一个函数,使用类似的东西:

var delay_func = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

但是,我被要求在每个函数中附加一个callAfter 'sub-function'以方便调用:

<function_name>.callAfter(milliseconds, param1, param2, ...);

我们知道如果我们向 Function.prototype 添加一个函数,它就可以在所有函数上调用。 所以我们使用这个代码:

Function.prototype.callAfter = function (time, ...params) {
  setTimeout(this(...params), time);
}

现在定义的任何函数都有 callAfter 方法。

例如:

function sum(a, b) {
  console.log('Sum is: ', a + b);
}

sum.callAfter(500, 3, 2) // output => Sum is: 5

或者:

function difference(a, b) {
  console.log('Difference is: ', a-b);
}

difference.callAfter(500, 3, 2) // output => Difference is: 1

如果我清楚地理解了你应该使用的任务Function.prototype。 函数原型可帮助您实现可用于代码附加的每个函数的函数。

Function.prototype.callAfter = function(delay = 4, arg1, arg2) {
    setTimeout(() => {
        return  this.call(null,  arg1, arg2);
    }, delay)}


function summ ( arg1, arg2){
    console.log('summ',  arg1 + arg2);};


summ.callAfter(500, 5,6)

您可以通过向函数构造函数的原型对象添加一个方法来实现。这样任何创建的函数都可以继承该方法。它被称为 prototypal inheritance:

Function.prototype.callAfter = function(delay, ...args) {
    setTimeout(() => this(...args), delay)
};