Reputation: 4306
Can someone explain to me why x is undefined? Shouldn't be 123?
doSomething = (function(x) {
alert(x)
})();
doSomething(123);
Upvotes: 0
Views: 87
Reputation: 4306
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")
Upvotes: 0
Reputation: 3031
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.
Upvotes: 2
Reputation: 227260
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);
Upvotes: 4