了解Javascript中的匿名函数

了解Javascript中的匿名函数,javascript,anonymous-function,Javascript,Anonymous Function,假设有一个函数: function doSomething(){ attachEvent("click", function(){ //there is a lot of code in this anonymous function //It may need to be defined somewhere else as a named function doSomethingElse = variabl

假设有一个函数:

function doSomething(){
    attachEvent("click", function(){
         //there is a lot of code in this anonymous function
         //It may need to be defined somewhere else as a named function             
         doSomethingElse = variable;
    });
}
如何在其他地方定义它并传入变量

function doSomething(){
     //this fires straight away 
     attachEvent("click", doNamedFunction(this.variable)); 
}

function doSomething(){
    //works but arguments aren't being passed
    attachEvent("click", doNamedFunction);
}

//I am defined as a named function instead of an anonymous function
function doNamedFunction(arg){
     doSomethingElse = arg;
     //do lots of other stuff below
}
因此,问题是如何声明命名函数并传递参数来代替匿名函数,还是始终需要使用匿名函数作为回调函数


非常感谢

您必须将函数包装在匿名函数中,或者使用较新浏览器中提供的
.bind()
API:

    attachEvent("click", doNamedFunction.bind(undefined, this.variable));

.bind()
调用返回一个函数,该函数将调用带有
未定义的
的“doNamedFunction”,作为
此值和给定参数。除了一些(有趣的)细节,您可以将
.bind()
看作是为您创建匿名函数的一种机制。

非常感谢!我想我将把这个函数包装成一个匿名函数。与event hanlding无关,但需要注意的是,较新版本的setTimeout允许使用…rest参数<代码>设置超时(函数(a,b,c){console.log(a,b,c);},1,'seven','seek','seek','nine')
认为它值得一提,因为它是新的,不需要包装或绑定,但可以用于类似的情况。@MattKenefick是的,但浏览器支持(尤其是跨移动浏览器)似乎不太确定。