问题
var test = function(a, b) { return a + b; };
setTimeout(test(2, 3), 3000);
it shows some type error
回答1:
There are at least two ways to achieve this.
The first one just fires the test
function inside of a new anonymous function passed as callback to the setTimout
.
The second one uses .bind
to partially apply the test
function.
var test = function(a, b) {
console.log(a + b);
return a + b;
};
setTimeout(() => {
test(2, 3);
}, 3000);
setTimeout(test.bind(null, 2, 3), 3000);
And if you don't like the first (in this case meaningless) argument null
of .bind
as I do, then you can use some library that provides you with partial application functionality or you can write your own function that performs partial application.
const partial = (fn, ...firstArgs) => (...secondArgs) =>
fn(...firstArgs, ...secondArgs);
var test = function(a, b) {
console.log(a + b);
return a + b;
};
setTimeout(partial(test, 2, 3), 3000);
回答2:
This is the right way to call an external function inside setTimeout
var test = function(a, b) { return a + b; };
setTimeout(function() {test(2, 3)} , 3000)
来源:https://stackoverflow.com/questions/50540257/how-to-pass-this-function-into-settimeout-with-parameters