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?

JS雑記1 - スコープについての理解

Posted at

スコープ問題において var でも解決できるが非推奨。また、他に基本に忠実で最適な解決策はある


サンプルコード

以下のようなコードで考える

  • このコードにおいて ReferenceError が出てしまうのは変数 a がブロックスコープに属する関係で参照できないのが原因と分かる
function fn() {
  if(true) {
    let a = 'fn called';
  }
  return a; //=> ReferenceError: a is not defined
}

const result = fn();
console.log(result);
  • "ブロックスコープ"が原因であるならば var の特性である「ブロックスコープを無視する」で解決可能
    • ただ var 自体が非推奨であるのと関数スコープ内のスコープ汚染の原因にもなるので好ましくない。

【メモ】

  • 関数宣言もブロックスコープに属さない特性を持つ(そもそもグローバルスコープだから)
    • 関数式は違う

【非推奨】varで解決する

function fn() {
  if(true) {
      var a = 'fn called';
  }
  return a;
}

const result = fn();
console.log(result);

【解決策】参照元と参照先のスコープを合わせる

  • 基本的な話『参照元と参照先のスコープを合わせれば良い』(参照元 = 宣言元)
    • JS なら undefined が自動で入る
    • Ruby だと nil を入れなければならないかもしれない?
function fn() {
  let a;
  if(true) {
      a = 'fn called';
  }
  return a;
}

const result = fn();
console.log(result);
0
0
2

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?