简体   繁体   English

如何将参数传递给javascript匿名函数

[英]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 ),但是没有传递任何参数,因此xundefined

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.

相关问题 如何将参数传递给匿名Javascript函数? - How do I pass argument to anonymous Javascript function? 将参数传递给匿名函数 - Pass an argument to anonymous function 如何将“回调”数组参数传递给匿名函数? - How to pass the 'callbacks' array argument to an anonymous function? JavaScript:如何将匿名函数作为函数参数传递? - JavaScript: How to pass an anonymous function as a function parameter? 如何将字符串的匿名数组传递给JavaScript函数? - How to pass an anonymous array of strings to a JavaScript function? 如何通过值将变量传递给匿名javascript函数? - How to pass a variable by value to an anonymous javascript function? 如何将变量从函数作为参数传递给匿名函数以充当变量 - How to pass a variable from a function as an argument to an anonymous function to work as a variable 如何在JavaScript函数中将“ this”作为参数传递? - How to pass `this` as an argument in javascript function? 如何将jQuery .click()的事件参数传递给非匿名函数 - How to pass the event argument of jQuery .click() to a non-anonymous function 如何在Javascript接口中将Javascript函数作为参数传递? - How to pass a Javascript function as an argument in Javascript Interface?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM