SUA 정보보안/JavaScript
[ JavaScript ] JS Hosting이란?
호IT
2021. 2. 15. 20:06
- Hosting
변수나 함수의 선언문을 유혀범위의 최상단으로 올려 변수나 함수를 선언하기 이전에도 사용할 수 있도록 해주는것입니다.
- 변수 Hosting
console.log(test); // 결괏값: undefined
var test = "FU11_M00N";
console.log(test); // 결괏값: FU11_M00N
name이라는 변수가 선언되기 전에 호출하면 에러가 아닌 undefined를 출력합니다.
var test;
console.log(test); // 결괏값: undefined
test = "FU11_M00N";
console.log(test); // 결괏값: FU11_M00N
자바스크립트의 Hoisting 특성은 유효범위의 최상단으로 올리기때문에 위의 예제와 동일한 효과가 발생합니다.
- 함수 Hoisting
test();
function test() {
console.log(hello); // 결과 : undefined
var hello = 'test';
console.log(hello); // 결과 : test
}
함수 또한 선언되기 전에 사용 가능합니다.
test(); // Uncaught TypeError: test is not a function 에러
var test = function() {
console.log(hello); // 결과 : undefined
var hello = 'test';
console.log(hello); // 결과 : test
}
하지만 위의 예제처럼 함수를 변수에 넣어 사용하면 함수 Hoisting이 발생하지않고 에러가 발생하게 됩니다.