我开始更详细地研究 JS,在测试了一些代码之后,我想到了这种情况:
var hello = function ()
{
console.log(arguments);
return (function(x,y){console.log(arguments);return x*y;});
}();
console.log(hello(2,5));
控制台输出如下:
[object Arguments] { ... }
[object Arguments] {
0: 2,
1: 5
}
10
谁能解释一下这种行为,因为我无法理解它。
我知道第一个函数是一个 IIFE,它在创建时立即执行。我唯一的问题是传递的参数如何传递给内部函数?
提前感谢您提供的信息和意见
最佳答案
好吧,让我看看我能不能为你打开这个:
var hello = function ()
{
console.log(arguments);
return (function(x,y){
console.log(arguments);
return x*y;
});
}();
console.log(hello(2,5));
首先,我要将 IFFE 拆分成一个函数语句。它的工作方式相同,但更像传统代码:
// Create our function
function action(x, y) {
console.log(arguments);
return x*y;
}
var hello = function ()
{
console.log(arguments);
//Here we are returning a REFERENCE to a function that already exists.
// We are *not* running the `action` function -- just getting its
// reference so it can be called later.
return action;
}();
// At this point in time, if you did a
console.log(hello)
// You'd see that it just points to the `action` function -- since that is what the
// IIFE returned.
console.log(hello(2,5));
值 hello
现在是我们的 action
函数。
IFFE语法有以下优点:
- 因为它是一个匿名函数,所以您不会使用名称或弄乱全局对象。
- 代码更“内联”,而不是分成两个独立的部分。
顺便说一句,如果我解释一下函数语句
和函数表达式
之间的区别,可能会有帮助。
函数语句如下所示:
function functionStatemnt() {
...
}
函数语句在编译完成时可用。该代码不需要执行即可使用。
函数表达式更像是:
var functionExpression = function() {
...
};
IFFE 是一个立即调用的函数表达式。为您提供一种创建作用域和“隐藏”变量的方法。
var myCounter = function() {
var counter = 0;
return function() {
return counter++;
}
}
console.log(myCounter());
console.log(myCounter());
console.log(myCounter());
关于javascript - JS IIFE 和带参数的内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23135009/