ReferenceError: "x" is not defined

λ©”μ‹œμ§€

ReferenceError: "x" is not defined

μ—λŸ¬ νƒ€μž…

무엇이 잘λͺ»λ˜μ—ˆμ„κΉŒ?

μ‘΄μž¬ν•˜μ§€ μ•ŠλŠ” λ³€μˆ˜λ₯Ό μ°Έμ‘°ν•˜λŠ” 곳이 μžˆμŠ΅λ‹ˆλ‹€. 이 λ³€μˆ˜λŠ” μ„ μ–Έλ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€. λ˜λŠ”, ν˜„μž¬ μŠ€ν¬λ¦½νŠΈλ‚˜ scope μ—μ„œ μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ„λ‘ ν•΄μ•Όν•©λ‹ˆλ‹€.

Note: λΌμ΄λΈŒλŸ¬λ¦¬(예λ₯Ό λ“€λ©΄ jQuery와 같은)의 λ‘œλ”©μ€, λ°˜λ“œμ‹œ μ½”λ“œμ—μ„œ  "$"와 같은 λΌμ΄λΈŒλŸ¬λ¦¬ λ³€μˆ˜μ— μ ‘κ·Όν•˜κΈ° 이전에 μˆ˜ν–‰λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€. 라이브러리λ₯Ό λ‘œλ”©ν•˜λŠ” <script> νƒœκ·Έκ°€ κ·Έ λ³€μˆ˜λ₯Ό μ‚¬μš©ν•˜λŠ” μ½”λ“œλ³΄λ‹€ μ•žμ— μœ„μΉ˜ν•˜λ„λ‘ ν•˜μ„Έμš”.

예

μ„ μ–Έλ˜μ§€ μ•Šμ€ λ³€μˆ˜

foo.substring(1); // ReferenceError: foo is not defined

"foo" λ³€μˆ˜λŠ” 어디에도 μ„ μ–Έλ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. String.prototype.substring() λ©”μ†Œλ“œκ°€ μž‘λ™ν•˜λ„λ‘ ν•˜κΈ° μœ„ν•΄μ„œλŠ” λ¬Έμžμ—΄μ„ ν•„μš”λ‘œ ν•©λ‹ˆλ‹€.

var foo = "bar";
foo.substring(1); // "ar"

잘λͺ»λœ μŠ€μ½”ν”„

λ³€μˆ˜λŠ” ν˜„μž¬μ˜ μ‹€ν–‰ 흐름 λ‚΄μ—μ„œ 이용 κ°€λŠ₯ν•΄μ•Όν•©λ‹ˆλ‹€. ν•¨μˆ˜ 내뢀에 μ •μ˜λœ λ³€μˆ˜λŠ” λ‹€λ₯Έ μ™ΈλΆ€μ˜ ν•¨μˆ˜μ—μ„œλŠ” μ ‘κ·Όν•  μˆ˜ μ—†μŠ΅λ‹ˆλ‹€. κ·Έ λ•Œλ¬Έμ—, λ³€μˆ˜λŠ” ν•¨μˆ˜μ˜ μŠ€μ½”ν”„ λ‚΄λΆ€μ—μ„œλ§Œ μ •μ˜ λ©λ‹ˆλ‹€.

function numbers () {
  var num1 = 2,
      num2 = 3;
  return num1 + num2;
}

console.log(num1); // ReferenceError: num1 is not defined

κ·ΈλŸ¬λ‚˜, ν•¨μˆ˜λŠ” λͺ¨λ“  λ³€μˆ˜μ™€ μ •μ˜λœ μŠ€μ½”ν”„ μ•ˆμ— μ •μ˜λœ ν•¨μˆ˜μ— μ ‘κ·Όν•  수 μžˆμŠ΅λ‹ˆλ‹€. λ”°λΌμ„œ, μ „μ—­μœΌλ‘œ μ •μ˜λœ ν•¨μˆ˜λŠ” 전역에 μ •μ˜λœ λͺ¨λ“  λ³€μˆ˜μ—λ„ μ ‘κ·Όν•  수 μžˆμŠ΅λ‹ˆλ‹€.

var num1 = 2,
    num2 = 3;

function numbers () {
  return num1 + num2;
}

console.log(num1); // 2

μ°Έμ‘°