LoginSignup
2
1

More than 1 year has passed since last update.

このJavaScriptのコードの出力結果が本当に理解できないから頑張って解説

Last updated at Posted at 2021-07-16

function test(){alert("test1")};
{
  var a={};
  a.abc = test;
  test=()=>alert("test2");
  a.abc(); // =>test1
  a.abc = test;
  a.abc(); // =>test2
}

と実行結果がなるらしい。。。。。

なんでやねん!!!!!


function test(){alert("test1")};
{
  var a={};
  a.abc = test;
  test=()=>alert("test2");
  a.abc(); // => test関数を上書きした感じだから、test2じゃないの?
  a.abc = test;
// なんでこのコードを
  a.abc(); // =>test2
}

function test(){alert("test1")};

test=()=>alert("test2");
はおそらく異なる関数オブジェクトなのであろう。

だけど、んーなんか府に落ちない。
何が分からないのかが分からない。。。。

多分答えはこう


function test(){alert("test1")};
{
  var a={};
  a.abc = test; 
// この時点でa.abcのtestの中身は{alert("test1")}
  test=()=>alert("test2");
// test関数を定義
// テスト関数の中身は確かに書き換わってるが
// a.abcのtest関数の中身に限定して言うと、
// a.abcのtest関数の中身は{alert("test1")}
  a.abc(); // =>test1
// a.abcのtestの中身は{alert("test1")}
  a.abc = test;
//   test=()=>alert("test2");
// この記述により確かにtest関数自体は書き換わってるので
// a.abcを再定義することによって
// a.abcのtestメソッドが書き変わる
  a.abc(); // =>test2
// 実行結果が変わる
}

考え方のコツとしては
ただのtest関数なのか、
a.abcのtestメソッドなのかを
しっかりと分けて考えるのが大切。

にしてもjs初学者の自分はなんか慣れない。。。。
これから慣れていこう。

2
1
7

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
2
1