포도가게의 개발일지

[Java Script]호이스팅, 함수 선언문 vs 함수 표현식, this, Promise 본문

[JS,TS,Node]

[Java Script]호이스팅, 함수 선언문 vs 함수 표현식, this, Promise

grape.store 2022. 2. 4. 18:14
반응형

호이스트(hoisting)

function getX() {
  console.log(x); // undefined
  var x = 100;
  console.log(x); // 100
}
getX();

// error가 안나는 이유는 JS는 호이스팅을 통해 선언과 할당부를 나누게 된다.

->호이스팅 되어 아래처럼 바뀌게 된다.
function getX() {
  var x;
  console.log(x); // undefined
  x = 100;
  console.log(x); // 100
}
getX();

함수 선언문 vs 함수 표현식

- 함수는 함수 이름으로 호출되는게 아니라 식별자를 통해 호출 된다.

- 함수 선언문에 경우 암묵적으로 함수이름을 가진 식별자를 함수가 포함된 스코프에 암묵적으로 생성한다.

// 함수 포현식
//  식별자           함수 이름
// 여기까지가 표현식       이부분은 익명함수
var add = function add(x, y) {
  return x + y;
}

// 함수 호출
console.log(add(2, 5)); // 7



// 함수 선언문
function foo() {
  console.log("foo");
}
foo(); // "foo"


// f: 식별자, add: 함수 이름
var f = function add(x, y) {
  return x + y;
};

// 식별자로 함수를 호출한다
console.log(f(2, 5)); // 7

console.log(add(2, 5)); // ReferenceError: add is not defined

This

- 자바스크립트에서 모든 함수는 실행될 때마다 함수 내부에 this라는 객체가 추가(객체가 무엇이냐 속성과 메소드다)된다. arguments라는 유사 배열 객체와 함께 함수 내부로 암묵적으로 전달되는 것이다. 그렇기 때문에 자바스크립트에서의 this는 함수가 호출된 상황에 따라 그 모습을 달리한다.

 

예제)

var myObject = {
  name: "foo",
  sayName: function() {
    console.log(this);
  }
};
myObject.sayName();
// console> Object {name: "foo", sayName: sayName()}

------------------------------------------------------------------------------------------

var value = 100;
var myObj = {
  value: 1,
  func1: function() {
    console.log(`func1's this.value: ${this.value}`);

    var func2 = function() {
      console.log(`func2's this.value ${this.value}`);
    };
    func2();
  }
};
------------------------------------------------------------------------------------------
myObj.func1();
// console> func1's this.value: 1
// console> func2's this.value: 100


var Person = function(name) {
  console.log(this);
  this.name = name;
};

var foo = new Person("foo"); // Person
console.log(foo.name); // foo

Promise

why?

- 초기에는 콜백 함수하는 정도였지만 복잡도가 높아지면서 콜백 중첩(callback hell)이 생기게 되면서 코드가 너무 복잡해졌다. 이러한 이유로 Promise 패턴을 이용하여 가독성 좋게 하기 위해 사용된다.

 

프로미스 상태 처리

  • pending(대기) : 처리 안끝남
  • fulfilled(이행) : 처리 완료
  • rejected(거부) : 처리 실패

function arriveAtSchool_tobe_adv() {

		// 간단한 Promise 선언 예제
		// new Promise(호출 함수);
    return new Promise(function(resolve, reject){
  	// Promise 즉 처리 되면 알려줄게 약속하는 것
    // 비동기 처리를 위해 setTimeout(작동, 시간) 사용
    // 시간이 지나면 작동부가 실행된다(queue에 들어오는거지 바로 실행도 안됨)
        setTimeout(function() {
            var status = Math.floor(Math.random()*2);
            if(status === 1) {
	            // resolve를 호출 -> then 실행 매개변수 넘겨줌
                resolve("학교에 도착했습니다.");
            } else {
	            // reject를 호출 -> catch 실행 매개변수 넘겨줌            
                reject(new Error("중간에 넘어져 다쳤습니다."));
            }
        }, 1000);
    });
}



arriveAtSchool_tobe_adv()
// 정상적으로 resolve가 호출되면 then
.then(function(res){
    console.log(res);
    study();
})
// 비정상적으로 reject가 호출되면 catch가 호출된다.
.catch(function(err){
    console.log(err);
    cure();
});

function cure() {
    console.log("양호실에 가서 약을 발랐습니다.");
}

 

Promise 체이닝

  • Promise retrun값은 기본 자료형이 아니라 Promise 객체이기 때문에 가능하다
  • 체이닝 기법을 이용하여 콜백 지옥에서  탈출 할 수 있다.
add(1,1)
.then(function(res){ // res: 2
    return res + 1; // 2 + 1 = 3
})
.then(function(res){ // res: 3
    return res * 4; // 3 * 4 = 12
})
.then(function(res){ // res: 12
    console.log(res); // 12 출력
});
// 한번이라도 rejected걸리면 바로 마지막 catch구문이다.
// error처리에 좋다.

goToSchool()
.then(function(){
    return arriveAtSchool();
})
.then(function(){
    return studyHard();
})
.then(function(){
    return eatLunch();
})
.catch(function(){
    leaveEarly();
});

'[JS,TS,Node]' 카테고리의 다른 글

[Node] 작동 원리  (0) 2022.02.09
[Java Script]생성자 함수, Closure, generator  (0) 2022.02.08
[Java Script] V8엔진 빌드과정  (0) 2022.02.04
Call stack && Event loop  (0) 2021.12.30
Vue CORS Error on Mac  (0) 2021.12.18
Comments