开发者

How to deal with anonymous functions in javascript functions?

I need to store an anonymous function passed as argument of my "named" func开发者_开发知识库tion in Javascript, and then call it later.

How can I do this? I already know how to pass an anonymous function as an argument, but I don't know how to deal with it when I'm "on the other side" of the code.

Thank you


Functions in JavaScript are first-class members which means that you can work with them just as you would any other data type in the language - you can pass them as arguments, keep them as member variables inside of other functions, return them from functions etc.

In the case you've asked about, it works just like any other named variable with the neat addition that you can invoke the function as below since it is a function:

function myFunc(anonymous){
    var arg1;
    anonymous(arg1);
}

myFunc(function(arg1){console.log(arg1)});


Just call it using the name of the parameter.

function callThisLater(laterFunction) {
  // ...
  laterFunction(args);
}

callThisLater(function (arg1) {
    alert("We've been called!");
});


Here is basic example:

function Foo(func) {
    this.Func = func;
    this.Activate = function() {
        this.Func();
    };
}

var foo = new Foo(function() { alert("activated"); });
foo.Activate();

I believe that what you missed is using the () to "activate" the function - as far as I understand you reached the point of "storing" the function to variable.


can you assign your anonymous function passed as an argument to a named function to a global variable inside the named function and then can used the global variable as a reference to anonymous function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜