0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

関数の中にある関数と実引数の関係 JavaScript

Last updated at Posted at 2023-07-08

首題の通り、関数の中にある関数と実引数の関係について、
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:
ご指摘や考察がありましたら、ご教示ください。
宜しくお願い致します

以上、

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?