JavaScript では、「()」は関数呼び出し演算子です。したがって、「()」を呼び出すたびに、この演算子の前に関数を呼び出そうとします。あなたの場合、追加する関数が割り当てられています。各関数に名前を付けて、非常に理解しやすいようにします。
var i = 0;
var add = function one() {
++i;
return function two() {
i++;
return function three() {
i++;
add();
}
}
};
// This will execute function one
// and return function two.
add();
// This will execute function one and two,
// return function three
add()();
// This will execute function one, two, three,
// return function two. Why?
// Because in function three, we call add() which will execute
// function one and return function two as I mentioned above.
add()()();
それでは、関数呼び出しを本当に理解しているかどうか見てみましょう。
var i = 0;
var add = function one() {
i++;
return function two() {
i++;
return function three() {
i++;
}
}()
};
無限ループを避けるために関数 3 内の関数 add() を削除し、関数 2 の後に "()" を追加します。では、今 add() を呼び出すとどうなるでしょうか?
// This will execute function one and return function two,
// function two will invoke itself because of "()" at the end
// I added and return function three. So call add() will
// execute function one and function two, return function three.
// So i = 2 in this case.
add();
自信が持てるまで、これらの関数呼び出しを 1 日中いじることができます。