Front-End 면접 질문 대비 Part2 (Promise, Arrow Function, Prototype)

이희제·2021년 1월 2일
22

직무 면접 대비

목록 보기
2/6

직무 면접 대비 파트 2입니다.


Promise

✅ 자바스크립트에서는 대부분의 작업들이 비동기적으로 이루어집니다.

=> Promise 패턴을 사용하면 이런 비동기적 처리를 컨트롤하기 쉬워집니다.

//Promise 선언
var _promise = function (param) {

	return new Promise(function (resolve, reject) {

		// 비동기를 표현하기 위해 setTimeout 함수를 사용 
		window.setTimeout(function () {

			// 파라메터가 참이면, 
			if (param) {

				// 해결됨 
				resolve("해결 완료");
			}

			// 파라메터가 거짓이면, 
			else {

				// 실패 
				reject(Error("실패!!"));
			}
		}, 3000);
	});
};

//Promise 실행
_promise(true)
.then(function (text) {
	// 성공시
	console.log(text);  // resolve에 넘겨진 값이 들어오게 된다.
}, function (error) {
	// 실패시 
	console.error(error); //reject에 넘겨진 값이 들어오게 된다.
});

참고: https://programmingsummaries.tistory.com/325


Promise의 3가지 상태

  • Pending (대기)

아래와 같이 new Promise()를 호출하면 Pending 상태가 됩니다.

new Promise();

new Promise()를 선언할 때 콜백 함수를 선언할 수 있고 콜백 함수의 인자는 resolve, reject 입니다.

new Promise(function(resolve, reject) {
  resolve();
});

❓여기서 콜백 함수란❓

=> javascript에서는 callback 함수는 다른 함수의 매개변수로 함수를 전달하고, 어떠한 이벤트가 발생한 후 매개변수로 전달한 함수가 다시 호출되는 것을 의미합니다.

[예시]

function square(x, callback) { 
  setTimeout(callback, 100, x*x); 
} 
square(2, function(number) { 
  console.log(number); 
});

출처: https://beomy.tistory.com/10 [beomy]

‼️ 콜백 함수는 Closure(클로저)입니다.

function callbackFunction (callback) {
    callback();
}

function testFunction() {
    var text = "callback function is closure";
    callbackFunction(function () {
        console.log(text);
    });
}


출처: https://beomy.tistory.com/10 [beomy]

callback 함수가 호출될 때는 text 변수가 존재하지 않습니다. 하지만 클로저이기 때문에 자신이 생성된 환경을 기억해 text를 정상적으로 출력합니다.


  • Fulfilled (이행)

아래와 같이 resolve를 실행하면 Fulfilled 상태가 됩니다.

new Promise(function(resolve, reject) {
  resolve();
});

  • Rejected (실패)

콜백 함수 인자 중 reject를 실행하면 Rejected 상태가 됩니다.

new Promise(function(resolve, reject) {
  reject();
});


Arrow Function

✅ 화살표 함수는 항상 익명이고 자신의 this, argument, super, new.target을 바인딩하지 않습니다. (this 바인딩 안하는 것 중요!)

//ES6

const box6 = {
    color: "green",
    pos: 1,
    click: function () {
        
        document.querySelector(".green").addEventListener("click", () => {
            var str = "this is box number" + this.pos + this.color;
            // -> arrow function은 click 의 this를 가지고 올 수 있다. (from surrouding)
            alert(str);
        });
    },
};

box6.click();


//Another case


const box6 = {
    color: "green",
    pos: 1,
    click: () =>  {    // arrow function 으로 변경.  -> this는 외부 window를 가리킨다. (this 를 바인딩하지 않기 때문)
        
        document.querySelector(".green").addEventListener("click", () => {
            var str = "this is box number" + this.pos + this.color;
            alert(str);
        });
    },
};

box6.click();    // result: undefined

ProtoType

✅ 자바스크립트는 프로토타입 기반 언어입니다.

자바스크립트에서는 Prototype objectPrototype link 라는 것이 존재하고 이 둘을 합쳐서 Prototype이라고 합니다.

Prototype Object

객체는 함수(Function)로 생성됩니다.

함수가 정의될 때는 2가지 일이 일어납니다.

  1. 함수에 생성자 자격 부여
  1. 함수에 Prototype Object 생성 및 연결

출처: https://medium.com/@bluesh55/javascript-prototype-이해하기-f8e67c286b67


생성된 함수는 prototype을 통해서 Prototype Object에 접근 할 수 있고 이 객체는 constructorproto 를 가지고 있습니다.

여기서 proto는 Prototype Link 입니다.

function Heeje() {}  // 객체가 생성됩니다.

Person.prototype.name = "heeje";
Person.prototype.age = 26;
var clone1  = new Heeje();
var clone2 = new Heeje():
console.log(clone1.name); // => "heeje"

바로 앞에서 Prototype Object가 proto를 가지고 있다고 했습니다. 이것이 Prototype Link입니다.

앞서 보여드린 예제 코드에서 clone1 에는 name 이라는 속성이 없지만 값을 참조해서 출력해주는 것을 확인할 수 있습니다.

이것을 가능하게 해주는 것이 바로 Prototype Link 입니다.

__proto__는 객체가 생성될 때 조상이었던 함수의 Prototype Object를 가리킵니다.

clone1의 객체는 Heeje 함수로부터 생성되었기 때문에 HeeJe 함수의 Prototype Object을 가리킵니다.


clone1객체가 name를 직접 가지고 있지 않기 때문에 name 속성을 찾을 때 까지 상위 프로토타입을 탐색합니다.

최상위인 Object의 Prototype Object까지 도달했는데도 못찾았을 경우 undefined를 리턴합니다.

이렇게 proto속성을 통해 상위 프로토타입과 연결되어있는 형태를 프로토타입 체인(Chain)이라고 합니다.


마무리

오늘은 Promise, Arrow Function, Prototype에 대해서 알아보았습니다.

이상으로 면접 대비 정리글을 마칩니다. 😃

profile
남는 것을 좋아하는 프론트엔드 개발자입니다.

2개의 댓글

comment-user-thumbnail
2021년 1월 2일

면접 보시는군요. 화이팅 하세요🤗

답글 달기
comment-user-thumbnail
2021년 3월 23일

프로토타입 첫 설명부분 예시코드에서 Person.prototype.name 부분 Heeje.prototype.name으로 해야 되지 않을까요

답글 달기