JavaScript의 범위: 'var'의 이상한 동작
8338 단어 webdevjavascriptbeginners
JavaScript의 범위
글로벌 범위
예시:
var globalVariable = "I am a global variable";
let globalVariableDeclaredWithLet =
"I am a global variable declared with let keyword";
const globalConstant = "I am a global constant";
function globalFunction() {
console.log("I am a global function");
}
기능 또는 로컬 범위
예시:
function globalFunction() {
var localVariable = "I am a local variable";
let localVariableDeclaredWithLet = "I am a local variable declared with let";
function localFunction() {
console.log("I am a local function and I can be called within this function only");
}
localFunction(); // I am a local function and I can be called within this function only
}
// invoking localFunction outside the function
localFunction(); // ReferenceError: localFunction is not defined.
블록 범위:
예시:
if(true) {
let blockVariable = "I am a block variable";
let blockFunction = () {
console.log("I am a block function");
}
// blockFunction can be called here
blockFunction(); //I am a block function
}
// blockFunction cannot be called outside the block
blockFunction(); //ReferenceError: blockFunction is not defined
'var'의 이상한 동작
예시:
if (true) {
var iAmWeird = "I am weird and you can access me from outside this block.";
}
// iAmWeird can be accessed outside the block.
console.log(iAmWeird); // I am weird and you can access me from outside this block.
키워드 없이 선언됨
예시:
if (true) {
iAmWeird = "I am weird and you can access me from outside this block.";
function weirdFunction() {
console.log("I am a weird function and you can call me from outside this block");
}
}
console.log(iAmWeird); // I am weird and you can access me from outside this block.
weirdFunction(); // I am a weird function and you can call me from outside this block
let과 const
let 및 const는 이러한 유형의 var 동작을 구출합니다.
let과 const는 블록 범위를 유지합니다.
예시:
if (true) {
let iAmWeird =
"I am not weird and you cannot access me from outside this block.";
const weirdFunction = function () {
console.log("I am not a weird function and you cannot call me from outside this block");
};
}
console.log(iAmWeird); // ReferenceError: iAmWeird is not defined.
weirdFunction(); // ReferenceError: weirdFunction is not defined.
Reference
이 문제에 관하여(JavaScript의 범위: 'var'의 이상한 동작), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/baijanaththaru/scopes-in-javascript-weird-behavior-of-var-2el7텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)