IT/JS

"this" 키워드 퀴즈 4개 풀이 by Annie Liao

프티 2021. 8. 13. 16:07
반응형

https://dev.to/liaowow/take-this-quiz-understand-how-this-works-in-javascript-44dj

 

Take 'this' Quiz, Understand How 'this' Works in JavaScript

Among all the abstract ideas JavaScript has to offer, the 'this' keyword can be one of the most chall...

dev.to

 

Challenge #1

const call = {
  caller: "mom", 
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

call.says();

What will the code above log to the console?

(A) Hey, undefined just called.
(B) Hey, mom just called.
(C) Hey, caller just called.

 

풀이

dot notation으로 says 함수가 실행되었고, say 함수는 함수 선언식이므로 this를 인식한다. 따라서 this는 call이다.

따라서 정답은 B --> 정답!

 

Challenge #2

const call = {
  caller: "mom", 
  says: () => {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

call.says();

What will the code above log to the console?

(A) Hey, undefined just called.
(B) Hey, mom just called.
(C) Hey, caller just called.

 

풀이

1번과 비슷하지만 says 함수는 화살표 함수이기 때문에 this를 인식하지 못한다.

call 내부에 this.caller가 정의되어있지 않으므로 정답은 A --> 정답!

 

Challenge #3

const call = {
  caller: "mom", 
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

let newCall = call.says;

newCall();

What will the code above log to the console?

(A) Hey, undefined just called.
(B) Hey, mom just called.

 

풀이

call.says를 새로운 변수에 할당하고 변수를 일반 함수 실행하였다.

따라서 this는 전역 객체이므로 정답은 A --> 정답!

 

Challenge #4

function anotherCaller() {
  console.log(`${this.caller} called, too!`);
}

const call = {
  caller: "mom", 
  anotherCaller: anotherCaller,
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

let newCall = call.anotherCaller;

newCall();

What will the code above log in the console?

(A) mom called, too!
(B) Hey, mom just called.
(C) undefined called, too!

 

풀이

newCall를 일반 함수 실행하였으므로,

this는 전역 객체가 된다 따라서 정답은 C --> 정답!

반응형