반응형
자바스크립트에서 prototype을 활용하면 객체 간 상속이 가능해집니다. 이번 퀴즈에서는 프로토타입을 활용한 개념을 익히고 문제를 풀어보세요!
퀴즈를 위한 코드
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
};
const person1 = new Person("Alice");
const person2 = new Person("Bob");
console.log(person1.getName());
console.log(person2.getName());
Person.prototype.getName = function() {
return "Anonymous";
};
console.log(person1.getName());
console.log(person2.getName());
퀴즈 문제
- 위 코드를 실행하면 콘솔에 어떤 출력이 나올까요?
- a) Alice, Bob, Alice, Bob
- b) Alice, Bob, Anonymous, Anonymous
- c) Alice, Bob, Alice, Anonymous
- d) undefined, undefined, Anonymous, Anonymous
- Person.prototype.getName을 변경한 후에도 기존 객체의 메서드가 영향을 받는 이유는 무엇인가요?
- a) 프로토타입 체인의 동적 바인딩 때문
- b) getName()이 객체에 직접 정의되지 않았기 때문
- c) 기존 객체가 자동으로 새로운 메서드를 재정의하기 때문
- d) 객체가 변경 사항을 감지하여 동적으로 업데이트하기 때문
정답 및 해설
1번 문제 해설 (출력 결과 예상)
console.log(person1.getName()); // Alice
console.log(person2.getName()); // Bob
Person.prototype.getName = function() {
return "Anonymous";
};
console.log(person1.getName()); // Anonymous
console.log(person2.getName()); // Anonymous
- person1.getName()과 person2.getName()은 처음에는 각각 "Alice"와 "Bob"을 반환
- Person.prototype.getName이 변경된 후, 기존 객체들은 새롭게 정의된 메서드를 따르게 되어 "Anonymous"를 반환
정답: ✅ b) Alice, Bob, Anonymous, Anonymous
2번 문제 해설 (Person.prototype.getName을 변경한 후 기존 객체에 영향을 미치는 이유)
- 자바스크립트의 프로토타입 체인은 동적 바인딩을 사용합니다.
- 즉, 객체가 getName()을 호출할 때마다 현재 프로토타입 체인에서 해당 메서드를 찾아 실행합니다.
- Person.prototype.getName이 변경되면 기존 객체들도 이를 반영하게 됩니다.
정답: ✅ a) 프로토타입 체인의 동적 바인딩 때문
이 문제를 풀기 위해 필요한 자바스크립트 개념
- 프로토타입(Prototype)
- 프로토타입 체인(Prototype Chain)
- new 키워드와 생성자 함수
- 동적 바인딩
끝
반응형
'IT > Python Quiz' 카테고리의 다른 글
[javascript] 자바스크립트 코드 읽기 연습 - 초급 퀴즈12 (0) | 2025.02.14 |
---|---|
[javascript] 자바스크립트 코드 읽기 연습 - 초급 퀴즈10 (0) | 2025.02.14 |
[javascript] 자바스크립트 코드 읽기 연습 - 초급 퀴즈9 (0) | 2025.02.14 |
[javascript] 자바스크립트 코드 읽기 연습 - 초급 퀴즈8 (0) | 2025.02.14 |
[javascript] 자바스크립트 코드 읽기 연습 - 중급 퀴즈4 (0) | 2025.02.14 |
[javascript] 자바스크립트 코드 읽기 연습 - 중급 퀴즈3 (0) | 2025.02.14 |
[javascript] 자바스크립트 코드 읽기 연습 - 중급 퀴즈2 (0) | 2025.02.14 |
[javascript] 자바스크립트 코드 읽기 연습 - 중급 퀴즈1 (0) | 2025.02.14 |
댓글