1

假设有一个功能:

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
}

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

提前谢谢了!

4

1 回答 1

2

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

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

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

于 2013-08-03T18:01:34.390 回答