2026년 상식닷컴 선정 식당 & 카페 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요

자바스크립트에서 상속을 구현하는 방법은 무엇인가요?

_____
Q1: 자바스크립트에서 상속이란 무엇인가요?
A1: 자바스크립트에서 상속은 한 객체가 다른 객체의 속성과 메서드를 물려받아 재사용하는 개념입니다. 이를 통해 코드 중복을 줄이고 객체 간의 관계를 표현할 수 있습니다.

---

Q2: 프로토타입 기반 상속이란 무엇인가요?
A2: 자바스크립트는 프로토타입 기반 언어로, 객체가 프로토타입 객체를 통해 속성과 메서드를 상속받습니다. 즉, 객체는 자신의 프로토타입 체인을 따라 속성을 탐색하며 상속을 구현합니다.

---

Q3: ES5에서 상속을 구현하는 방법은 무엇인가요?
A3: ES5에서는 아래와 같이 생성자 함수와 프로토타입 체인을 활용하여 상속을 구현합니다.

```javascript
function Parent(name) {
this.name = name;
}

Parent.prototype.greet = function() {
console.log('Hello, ' + this.name);
};

function Child(name, age) {
Parent.call(this, name); // 부모 생성자 호출하여 this 초기화
this.age = age;
}

Child.prototype = Object.create(Parent.prototype); // 프로토타입 상속
Child.prototype.constructor = Child; // constructor 재설정

Child.prototype.showAge = function() {
console.log('Age: ' + this.age);
};

const child = new Child('Alice', 10);
child.greet(); // Hello, Alice
child.showAge(); // Age: 10
```

---

Q4: ES6에서 상속을 구현하는 방법은 무엇인가요?
A4: ES6에서는 `class`와 `extends` 키워드를 활용하여 보다 간결하게 상속을 구현할 수 있습니다.

```javascript
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log('Hello, ' + this.name);
}
}

class Child extends Parent {
constructor(name, age) {
super(name); // 부모 생성자 호출
this.age = age;
}
showAge() {
console.log('Age: ' + this.age);
}
}

const child = new Child('Alice', 10);
child.greet(); // Hello, Alice
child.showAge(); // Age: 10
```

---

Q5: 프로토타입 체인을 직접 수정해서 상속할 수도 있나요?
A5: 네, `Object.setPrototypeOf()` 또는 `__proto__`를 사용하여 직접 프로토타입을 설정할 수도 있지만 성능 저하 및 가독성 문제로 권장되지 않습니다. 대신 `Object.create()`나 ES6 클래스를 사용하는 방법이 더 안전합니다.

---

Q6: 다중 상속은 자바스크립트에서 구현할 수 있나요?
A6: 자바스크립트는 기본적으로 다중 상속을 지원하지 않습니다. 하지만 믹스인(mixin) 패턴이나 객체 합성(composition)을 통해 유사 다중 상속 효과를 낼 수 있습니다.

---

Q7: 믹스인(mixin)이란 무엇인가요?
A7: 믹스인은 여러 객체나 클래스의 메서드를 하나의 객체에 복사하여 사용하는 패턴입니다. 상속이 아닌 조합을 통해 기능을 확장하는 방식입니다.

```javascript
const canEat = {
eat() {
console.log('Eating');
}
};

const canWalk = {
walk() {
console.log('Walking');
}
};

const person = Object.assign({}, canEat, canWalk);
person.eat(); // Eating
person.walk(); // Walking
```

---

Q8: 상속 시 생성자 호출은 어떻게 하나요?
A8: ES5에서는 부모 생성자를 자식 생성자 내에서 `Parent.call(this, args)`로 호출하고, ES6에서는 `super(args)`를 사용합니다. 이는 부모 클래스가 자신의 속성을 올바르게 초기화하도록 합니다.

---

Q9: 자바스크립트의 상속이 클래스 기반 언어와 다른 점은?
A9: 자바스크립트는 클래스 기반이 아닌 프로토타입 기반 언어입니다. 클래스는 ES6에서 편의 문법으로 도입된 것이며, 실제 구현은 프로토타입 체인을 사용합니다. 이 때문에 동적으로 프로토타입을 변경할 수도 있습니다.

---

Q10: 요약하면 자바스크립트 상속 구현 방법은?
A10:
- ES5: 생성자 함수 + `Object.create()`로 프로토타입 연결 + `Parent.call(this)`로 부모 생성자 호출
- ES6: `class` 키워드와 `extends`, `super()` 사용
- 믹스인 또는 조합으로 복합 기능 구현 가능

이상으로 자바스크립트 상속 구현 방법에 대한 주요 내용을 정리했습니다.
자바스크립트에서 상속을 구현하는 방법은 여러 가지가 있으며, ES5 이전과 이후의 문법에 따라 다르게 접근할 수 있습니다.

여기서는 다양한 방법을 소개하고 각각의 장단점을 설명하겠습니다.

1. 프로토타입 기반 상속 (ES5 이전) 자바스크립트는 프로토타입 기반 언어입니다.

객체는 다른 객체를 프로토타입으로 가질 수 있으며, 이를 통해 상속을 구현할 수 있습니다.

```javascript function Parent() { this.parentProperty = 'I am a parent property'; } Parent.prototype.parentMethod = function() { console.log('This is a method from the parent'); }; function Child() { Parent.call(this); // 부모 생성자 호출 this.childProperty = 'I am a child property'; } // 프로토타입 체인 설정 Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child; Child.prototype.childMethod = function() { console.log('This is a method from the child'); }; // 사용 예 const childInstance = new Child(); console.log(childInstance.parentProperty); // 'I am a parent property' childInstance.parentMethod(); // 'This is a method from the parent' console.log(childInstance.childProperty); // 'I am a child property' childInstance.childMethod(); // 'This is a method from the child' ``` 장점: - 프로토타입 체인을 통해 메모리 효율적으로 메서드를 공유할 수 있습니다.

단점: - 코드가 복잡해질 수 있으며, 상속 관계를 이해하기 어려울 수 있습니다.



2. ES6 클래스 문법 ES6(ECMAScript 201

5)부터는 클래스 문법이 도입되어 상속을 보다 직관적으로 구현할 수 있습니다.

```javascript class Parent { constructor() { this.parentProperty = 'I am a parent property'; } parentMethod() { console.log('This is a method from the parent'); } } class Child extends Parent { constructor() { super(); // 부모 생성자 호출 this.childProperty = 'I am a child property'; } childMethod() { console.log('This is a method from the child'); } } // 사용 예 const childInstance = new Child(); console.log(childInstance.parentProperty); // 'I am a parent property' childInstance.parentMethod(); // 'This is a method from the parent' console.log(childInstance.childProperty); // 'I am a child property' childInstance.childMethod(); // 'This is a method from the child' ``` 장점: - 클래스 문법은 객체 지향 프로그래밍의 전통적인 개념을 따르므로 코드가 더 명확하고 가독성이 좋습니다.

- `super` 키워드를 사용하여 부모 클래스의 생성자와 메서드를 쉽게 호출할 수 있습니다.

단점: - ES6 이전의 코드와 호환되지 않으며, 구형 브라우저에서는 지원되지 않을 수 있습니다.



3. Object.create()를 통한 상속 `Object.create()` 메서드를 사용하여 객체를 생성하고, 이를 통해 상속을 구현할 수도 있습니다.

```javascript const parent = { parentProperty: 'I am a parent property', parentMethod: function() { console.log('This is a method from the parent'); } }; const child = Object.create(parent); child.childProperty = 'I am a child property'; child.childMethod = function() { console.log('This is a method from the child'); }; // 사용 예 console.log(child.parentProperty); // 'I am a parent property' child.parentMethod(); // 'This is a method from the parent' console.log(child.childProperty); // 'I am a child property' child.childMethod(); // 'This is a method from the child' ``` 장점: - 간단하고 직관적으로 객체를 생성할 수 있습니다.

- 상속 구조를 명확히 할 수 있습니다.

단점: - `Object.create()`는 생성자 함수와는 다르게 인스턴스를 생성하는 방식이 아니므로, 생성자 패턴을 사용하는 경우와는 다르게 동작할 수 있습니다.

결론 자바스크립트에서 상속을 구현하는 방법은 다양하며, 각 방법은 특정 상황에 따라 장단점이 있습니다.

ES6 클래스 문법은 현대적인 자바스크립트 개발에서 가장 많이 사용되며, 코드의 가독성과 유지보수성을 높이는 데 기여합니다.

그러나 기존의 프로토타입 기반 상속이나 `Object.create()`를 사용하는 방법도 여전히 유용하며, 상황에 따라 적절한 방법을 선택하는 것이 중요합니다.

작성자: 박하윤 [비회원] | 작성일자: 1년 전 2024-09-08 14:47:23
조회수: 210 | 댓글: 0 | 좋아요: 0 | 싫어요: 0
내용이 부정확하다면 싫어요를 클릭해주세요.