Chapter 3: The Scope Chain - hochan222/Everything-in-JavaScript GitHub Wiki

Global Unshadowing Trick

var studentName = "Suzy";
function printStudent(studentName) { 
  console.log(studentName); 
  console.log(window.studentName);
}
printStudent("Frank");
// "Frank"
// "Suzy"
var one = 1;
let notOne = 2; 
const notTwo = 3; 
class notThree {}

console.log(window.one);      // 1
console.log(window.notOne);   // undefined
console.log(window.notTwo);   // undefined
console.log(window.notThree); // undefined
45

Copying Is Not Accessing

var special = 42;
function lookingFor(special) { 
    var another = {
        special: special
    };

    function keepLooking() {
        var special = 3.141592;
        console.log(special); 
        console.log(another.special); // Ooo, tricky! 
        console.log(window.special);
    }
    keepLooking();
}

lookingFor(112358132134); 
// 3.141592
// 112358132134
// 42

Illegal Shadowing

let(λ‚΄λΆ€ λ²”μœ„)은 항상 μ™ΈλΆ€ λ²”μœ„μ˜ varλ₯Ό μ„€λ„μž‰ ν•  수 μžˆλ‹€. var(λ‚΄λΆ€ λ²”μœ„)λŠ” 사이에 ν•¨μˆ˜ κ²½κ³„κ°€μžˆλŠ” κ²½μš°μ—λ§Œ μ™ΈλΆ€ λ²”μœ„μ˜ let을 μ„€λ„μž‰ ν•  수 μžˆλ‹€.

Function Name Scope


var askQuestion = function ofTheTeacher() { 
  console.log(ofTheTeacher);
};

askQuestion();
// function ofTheTeacher()...

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

ofTheTeacherλŠ” μ™ΈλΆ€κ°€ μ•„λ‹Œ ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ μ„ μ–Έ 될뿐만 μ•„λ‹ˆλΌ 읽기 μ „μš©μœΌλ‘œλ„ μ •μ˜λœλ‹€.

var askQuestion = function ofTheTeacher() { 
  "use strict";
  ofTheTeacher = 42; // TypeError

  //..
};

askQuestion();
// TypeError

Arrow Functions

  1. ν™”μ‚΄ν‘œ ν•¨μˆ˜λŠ” 읡λͺ… ν•¨μˆ˜λ‘œλ§Œ μ‚¬μš©ν•  수 μžˆλ‹€. ( O / X )

    Arrow functions are lexically anonymous, meaning they have no directly related identifier that references the function. p.53