자바스크립트 호이스팅
뭐야?
어떻게 작동합니까?
수업 과정
범위
Scope defines where variables can be accessed or referenced.
블록
Block is the code found inside a set of curly braces {}
function greet() {
b = 'hello';
console.log(b); // hello
var b;
}
greet();
글로벌 범위
Global scope are variables that are declared outside of blocks.
const color = 'blue';
const returnSkyColor = () => {
return color; // blue
};
console.log(returnSkyColor()); // blue
블록 범위
Variables that are declared with block scope are known as local variables, because they are only available to the code that is part of the same block.
const logSkyColor = () => {
let color = 'blue';
console.log(color); // blue
};
logSkyColor(); // blue
console.log(color); // ReferenceError
범위 오염
Scope pollution is when we have too many global variables that exist in the global namespace, or when we reuse variables across different scopes.
let num = 50;
const logNum = () => {
num = 100; // Take note of this line of code
console.log(num);
};
logNum(); // Prints 100
console.log(num); // Prints 100
가변 호이스팅
Variable hoisting acts differently depending on how the variable is declared (var,let,const).
메모:
변수 변수
var foo;
console.log(foo); // undefined
foo = 'foo';
console.log(foo); // "foo"
변수 let & const
console.log(foo); // Uncaught ReferenceError: Cannot access 'foo' before initialization
let foo = 'bar'; // Same behavior for variables declared with const
함수 호이스팅
Function hoisting allows us to call a function before it is defined
foo(); // "foo"
function foo() {
console.log('foo');
}
BUT NOT Function Expressions
foo(); // Uncaught TypeError: foo is not a function
var foo = function () { }
bar(); // Uncaught ReferenceError: Cannot access 'bar' before initialization
let bar = function () { }
baz(); // Uncaught ReferenceError: Cannot access 'baz' before initialization
const baz = function () { }
클래스 호이스팅
var Frodo = new Hobbit();
Frodo.height = 100;
Frodo.weight = 300;
console.log(Frodo); // Output: ReferenceError: Hobbit is not defined
class Hobbit {
constructor(height, weight) {
this.height = height;
this.weight = weight;
}
}
게양 연습
1.
function func11(){
var a=5;
console.log(a, b);
var b=6;
}
func11();
2.
console.log(var1);
var var1 = 1;
function func(){
console.log(var1);
var var1 = 2;
console.log(var1);
}
var var1 = 3;
console.log(var1);
func();
3.
function func(){
//console.log(var1);
//console.log(let1);
if(true){
var var1 = 2;
let let1 = 23;
}
//console.log(var1);
//console.log(let1);
}
var var1 = 3;
func();
4.
func1();
func2();
function func1(){
console.log('func1');
}
var func2 = function(){
console.log('func2');
}
5.
var var1=2;
console.log(i);
for(var i=0; i<11; i++){
console.log('asdf');
}
console.log(i);
Reference
이 문제에 관하여(자바스크립트 호이스팅), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/vasconevesxd/javascript-hoisting-4lod텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)