JavaScript - 문제 미리보기
문제 622
hard
다음 코드의 실행 결과를 예측하세요:
```javascript
function Person(name) {
this.name = name;
}
Person.prototype.changeName = function(newName) {
this.name = newName;
}
const person1 = new Person("Alice");
const person2 = new Person("Bob");
person1.changeName = function(newName) {
this.name = "Mr. " + newName;
}
person1.changeName("Charlie");
person2.changeName("David");
console.log(person1.name + " and " + person2.name);
```
```javascript
function Person(name) {
this.name = name;
}
Person.prototype.changeName = function(newName) {
this.name = newName;
}
const person1 = new Person("Alice");
const person2 = new Person("Bob");
person1.changeName = function(newName) {
this.name = "Mr. " + newName;
}
person1.changeName("Charlie");
person2.changeName("David");
console.log(person1.name + " and " + person2.name);
```
정답: B
1) `person1`에게는 개별적으로 `changeName` 메서드가 재정의되어 "Mr. "를 앞에 붙입니다.
2) `person2`는 prototype의 원래 `changeName` 메서드를 사용하므로 단순히 이름만 변경됩니다.
3) 객체에 직접 추가된 메서드는 prototype의 같은 이름 메서드보다 우선순위가 높습니다.
4) 따라서 `person1.name`은 "Mr. Charlie", `person2.name`은 "David"가 됩니다.
2) `person2`는 prototype의 원래 `changeName` 메서드를 사용하므로 단순히 이름만 변경됩니다.
3) 객체에 직접 추가된 메서드는 prototype의 같은 이름 메서드보다 우선순위가 높습니다.
4) 따라서 `person1.name`은 "Mr. Charlie", `person2.name`은 "David"가 됩니다.
💡 학습 팁
이 문제를 포함한 JavaScript 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.