了解Javascript中的匿名函数

时间:2013-08-03 17:58:32

标签: 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 = 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
}

所以问题是如何声明命名函数并传递参数来代替匿名函数,或者你总是需要使用匿名函数作为回调..?

非常感谢提前!

1 个答案:

答案 0 :(得分:2)

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

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

.bind()调用返回一个函数,该函数将调用“doNamedFunction”并将undefined作为this值和您给定的参数。除了一些(有趣的)细节之外,您可以将.bind()视为为您创建匿名函数的机制。