简体   繁体   中英

How to pass argument to javascript anonymous function

Can someone explain to me why x is undefined? Shouldn't be 123?

doSomething = (function(x) {
   alert(x)
})();

doSomething(123);

doSomething isn't a function. It's undefined .

doSomething = (function(x) {
   alert(x)
})();

This declares an anonymous function, immediately executes it (that's what the () does), then sets doSomething to the return value - undefined . Your anonymous function takes one parameter ( x ), but nothing is passed to it, so x is undefined .

You probably want this:

doSomething = function(x) {
   alert(x)
};

doSomething(123);

You need to remove the parens, right now you define the function and immediately call it with an empty argument list. Change it to this:

doSomething = function(x) {
   alert(x)
}

And then you can call it.

Wouldn't this be the better way? let it init, then call it passing an argument?

doSomething = (function(x) {

    return(
            init = function(x){   

             alert(x)
            }
        )


})();

doSomething("test")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM