IT/JS

"this" 키워드 퀴즈 7개 풀이 (1~3번) by Dmitri Pavlutin

프티 2021. 8. 12. 23:13
반응형

https://dmitripavlutin.com/javascript-this-interview-questions/#question-1-variable-vs-property

 

7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them?

7 interview questions to challenge your knowledge on "this" keyword in JavaScript.

dmitripavlutin.com

위 사이트에서 정확한 this의 객체를 파악하는 능력을 기르기 위한 7가지 퀴즈가 있어 풀이해보려 한다.

 

아직 this를 찾는 일이 쉽지 않아 이렇게 문제를 보면 풀어보면서 꾸준히 연습해야겠다.

 

Question 1: Variable vs property

What logs to console the following code snippet(작은 조각):

const object = {
  message: 'Hello, World!',

  getMessage() {
    const message = 'Hello, Earth!';
    return this.message;
  }
};

console.log(object.getMessage()); // What is logged?

풀이

먼저 getMessage 함수의 실행 방식이 dot notation이므로,

getMessage 함수의 this는 object 객체이다.

 

따라서 정답은 'Hello, World!' --> 정답

 

Question 2: Cat name

What logs to console the following code snippet:

function Pet(name) {
  this.name = name;

  this.getName = () => this.name;
}

const cat = new Pet('Fluffy');

console.log(cat.getName()); // What is logged?

const { getName } = cat;
console.log(getName());     // What is logged?

풀이

cat이 new 키워드를 통해 새로운 빈 객체를 할당받았다.

 

따라서 getName이 함수 선언식이었다면 getName의 this는 cat이었겠지만,

getName은 화살표 함수이므로 this를 인식할 수 없기 때문에 함수 내에서 this.name을 찾을 수 없다.

 

따라서 getName이 실행된 컨텍스트에서 찾아야 하는데 this.name이 있으므로 정답은 'Fluffy' --> 정답

 

두 번째 로그는 { getName } = cat이 무슨 의도인지는 잘 모르겠지만,

getName 함수를 일반 함수 실행하였으므로 이때 this는 전역 객체라는 판단이 된다.

 

전역 변수 name이 없으므로 정답은 undefined가 아닐까..? --> ❌

☛ 내가 이해하지 못한 const { getName } = cat;은 바로 객체 구조 분해이다.

 

구조 분해 할당이라는 표현식을 객체에 적용할 때 사용한다.

cat 객체의 getName을 꺼내왔기 때문에 Pet 함수 밖에서 getName 함수를 실행할 수 있었던 것이다.

 

그리고 getName 함수는 클로저이기 때문에, this값을 해당 컨텍스트 안에서 찾을 수 있다.

또한 getName이 일반 실행 함수여도 cat의 this는 cat 객체로 고정되어있기 때문에 스코프 체인을 통해 상위 스코프에서 this를 찾는다.

 

Question 3: Delayed greeting

What logs to console the following code snippet:

const object = {
  message: 'Hello, World!',

  logMessage() {
    console.log(this.message); // What is logged?
  }
};

setTimeout(object.logMessage, 1000);

풀이

setTimeout 함수에서 object.logMessage를 일반 함수 실행하므로 this는 전역 객체이다.

따라서 정답은 undefined! --> 오.. 정답!

 

☛setTimeout은 object.logMessage를 콜백 함수로 사용하기 때문에 메소드 형식이 아닌 일반 함수 형식으로 실행시킨다.

 

Side challenge: how can you fix this code so that 'Hello, World!' is logged to console? Write your solution in a comment below!

 

나는 단순하게 전역 변수 message를 할당해주었지만,

코멘트에 정답이 있었다.

setTimeout(() => { object.logMessage }, 1000);

setTimeout 함수는 object.logMessage를 콜백 함수로 사용했는데,

콜백 함수 안에 object.logMessage를 넣어주자는 것이다.

 

나머지 문제는 다음 포스팅에서 계속하겠다.

 

반응형