如何将参数传递给 JS 函数而不将其包装在匿名函数中?

How do I pass a parameter into a JS function without wrap it in an anonymous function?

很长一段时间我都有这个问题:如何将参数传递给 JS 函数而不将其包装在匿名函数中?

让我们看一个例子:

var
x = 10,
foo = function( num ) {
    console.log("Number: " + num);
};

// This way works, but I wouldn't like to wrap it in an anonymous function
setTimeout(function() {
    foo( x );
}, 1000 );

// Is there a way to pass the 'x' parameter here?
setTimeout( foo, 2000 );

有没有办法在第二次 setTimeout 调用时传递参数?

在现代 Javascript 引擎中(MDN 也有一个 shim that makes this work in IE9 and older):

setTimeout( foo, 2000, x );

或使用bind, which is not quite as modern, but still modern enough to have no support in IE8 (again there is a shim on MDN):

setTimeout( foo.bind( null, x ), 2000 );

如果您通常使用上下文调用该函数,请将 null 替换为您希望 this 包含在您的函数中的任何内容。在您上面的示例中,null 效果很好。