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
-
νμ΄ν ν¨μλ μ΅λͺ ν¨μλ‘λ§ μ¬μ©ν μ μλ€. ( O / X )
Arrow functions are lexically anonymous, meaning they have no directly related identifier that references the function. p.53