[英]How to pass argument to javascript anonymous function
Can someone explain to me why x is undefined? 有人可以向我解释为什么x是未定义的吗? Shouldn't be 123?
不应该是123吗?
doSomething = (function(x) {
alert(x)
})();
doSomething(123);
doSomething
isn't a function. doSomething
不是函数。 It's undefined
. 它是
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
. 这将声明一个匿名函数, 立即执行它((即执行
()
),然后将doSomething
设置为返回值undefined
。 Your anonymous function takes one parameter ( x
), but nothing is passed to it, so x
is undefined
. 您的匿名函数采用一个参数(
x
),但是没有传递任何参数,因此x
是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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.