javascript 将参数传递给内联函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13994771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing Arguments into an Inline Function
提问by Flat Cat
I'd like to use an inline function with arguments to set a variable. Here is a boiled down version (which apparently is only pseudo code at this point) of what I'm attempting:
我想使用带参数的内联函数来设置变量。这是我正在尝试的简化版本(此时显然只是伪代码):
var something = 10;
var something_else = 15;
var dynamic_value = (function(something,something_else){
if(something == something_else){
return "x";
}else{
return "y";
}
})();
In this case, "dynamic_value" should be "y". The problem is that the variables "something" and "something_else" are never seen inside of this inline function.
在这种情况下,“dynamic_value”应该是“y”。问题是变量“something”和“something_else”从未出现在这个内联函数中。
How do you send arguments to an inline function?
如何向内联函数发送参数?
edit: I'm using jquery, although that may not really apply to this question.
编辑:我正在使用 jquery,尽管这可能不适用于这个问题。
回答by Matt Greer
Send them in when invoking the function
调用函数时发送它们
var dynamic_value = (function(something, something_else) {
...
})(value_for_something, value_for_something_else);
回答by closure
You will need to call it like this.
你需要这样称呼它。
var dynamic_value = (function(something,something_else){
if(something == something_else){
return "x";
}else{
return "y";
}
})(something,something_else);
The reason for this is when you are defining the same names in the function parameter, they are just the names of the parameters, the variables don't get inserted there. The last line is call to the function where actual variables are passed.
原因是当您在函数参数中定义相同的名称时,它们只是参数的名称,变量不会插入那里。最后一行是调用传递实际变量的函数。
Besides, you have just created a closure. The closure has access to all the variables declared in the function that contains it. Another interesting fact in this code is that variables defined at the containing function level are getting shadowed by the variables that are part of the closure function. The reason is obvious: the variable names at the closure is same as the variable names at the containing function.
此外,您刚刚创建了一个闭包。闭包可以访问包含它的函数中声明的所有变量。这段代码中另一个有趣的事实是,在包含函数级别定义的变量被作为闭包函数一部分的变量所掩盖。原因很明显:闭包处的变量名与包含函数处的变量名相同。
回答by Halcyon
I'm going to guess here that you want dynamic_value
to just bind to something
but not something_else
.
我将在这里猜测您dynamic_value
只想绑定到something
而不是something_else
.
var base_value = 10;
var something_else = 15;
var dynamic_value = (function(base_value){
return function (compare) {
if(base_value == compare){
return "x";
} else {
return "y";
}
};
})(base_value);
alert(dynamic_value(something_else)); // "y"
alert(dynamic_value(10)); // "x"