Swa*_*Rai 5 javascript chaining
编辑:这不是如何在setTimeout中传递参数的重复.实际上,我想知道如何编写一个函数,它将被调用作为预定义函数的方法,就像setTimeout API一样.
那么,我如何为函数'callAfter'编写一个实现,它允许在某些指定的持续时间之后使用某些参数调用任何函数,具有以下提到的语法:
示例:假设您有一个名为'sum'的函数,如下所示:
function sum(a, b) {
console.log('Sum is: ', a + b);
}
Run Code Online (Sandbox Code Playgroud)
现在你应该能够执行:sum.callAfter(5000,8,9);
应该在5秒后使用参数8和9调用函数'sum'.
Swa*_*Rai 11
使用函数原型获得它:
Function.prototype.callAfter = function(){
if(arguments.length > 1){
var args = Array.prototype.slice.call(arguments);
var time = args.splice(0,1);
var func = this;
setTimeout(function(){
func.apply(null, args);
}, time);
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
497 次 |
| 最近记录: |