首題の通り、関数の中にある関数と実引数の関係について、
JavasScriptのレキシカルスコープとスコープチェーンの考察にご利用ください。
外部スコープ、引数要素と関数コンテキスト内の外部変数との兼ね合いと位置付けについての考察にお使いいただけるかと存じます。
実行してみましょう
jsFiddle(https://jsfiddle.net/ )
JS Bin(https://jsbin.com/?html,js,output )
1.外側の関数の実引数は、内側の関数の仮引数に勝手に渡らない
function sample1(str) {
console.log(str);
function sample2(str) {
console.log(str);
}
sample2();
}
sample1('hello');
実行結果
"hello"
undefined
2.内側の関数に仮引数を除くと、レキシカルスコープにより、実引数が内側の関数に渡ってくる。
function sample1(str) {
console.log(str);
function sample2() {
console.log(str);
}
sample2();
}
sample1('hello');
実行結果
"hello"
"hello"
3.外側の関数で実引数をletで受け取るだけで、内側の関数の仮引数に渡ることはない。
function sample1(str) {
console.log(str);
let _str = str;
function sample2(_str) {
console.log(_str);
}
sample2();
}
sample1('hello');
実行結果
"hello"
undefined
4.外側の関数で実引数をletで受け取り、内側の関数で初期値として仮引数に渡せば良い。
function sample1(str) {
console.log(str);
let _str = str;
function sample2(str = _str) {
console.log(str);
}
sample2();
}
sample1('hello');
実行結果
"hello"
"hello"
NOTE:
ご指摘や考察がありましたら、ご教示ください。
宜しくお願い致します
以上、