
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
}
const me = new Person("sungu", 28);
console.log(me) // Person {name: 'sungu', age: 28}age: 28name: "sungu"[[Prototype]]: Object
- constructor는 인스턴스를 생성하고 초기화 하기 위한 특수한 메서드다.
- constructor는 이름을 변경할 수 없다.
- 2개 이상의 constructor를 사용하면 문법 에러가 발생한다.
class Bungeoppang {
constructor(shape, size, filling) {
this.shape = shape;
this.size = size;
this.filling = filling;
}
eat() {
console.log(`${this.size} 크기의 ${this.shape} 모양 붕어빵을 먹고 있습니다. 속재료: ${this.filling}`);
}
}
const myBungeoppang = new Bungeoppang('붕어', '중간', '팥');
1. 인스턴스 생성과 this 바인딩: 붕어빵 틀을 사용하여 붕어빵을 만들기 시작하는 단계
2. 인스턴스 초기화: 붕어빵 틀에 반죽과 속재료를 넣고 굽는 단계
3.인스턴스 반환: 완성된 붕어빵을 틀에서 꺼내는 단계
프로토타입 기반 상속 예제
const Animal = { speak() { console.log(`${this.name}가 소리를 냅니다.`); } }; // Animal을 프로토타입으로 하는 객체 생성 const dog = Object.create(Animal); dog.name = '바둑이'; dog.bark = function() { console.log(`${this.name}는 멍멍 짖습니다.`); }; dog.speak(); // 바둑이가 소리를 냅니다. dog.bark(); // 바둑이는 멍멍 짖습니다.프로토타입 기반 상속은 JavaScript의 근본적인 상속 방식으로, 객체 간의 직접적인 프로토타입 연결을 통해 상속을 구현한다.
클래스 기반 상속 예제
// 부모 클래스 정의 class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name}이(가) 소리를 냅니다.`); } } // Animal 클래스를 상속받는 Dog 클래스 정의 class Dog extends Animal { constructor(name, breed) { // 부모 클래스의 생성자 호출 super(name); this.breed = breed; } speak() { console.log(`${this.name}는 멍멍 짖습니다.`); } // 추가 메소드 정의 fetch() { console.log(`${this.name}가 물건을 가져옵니다.`); } } // 인스턴스 생성 const myDog = new Dog('바둑이', '진돗개'); myDog.speak(); // 바둑이는 멍멍 짖습니다. myDog.fetch(); // 바둑이가 물건을 가져옵니다.
- 클래스 기반 상속은 ES6에서 도입된 문법으로, 클래스와 상속 키워드를 사용하여 보다 직관적이고 명확하게 상속 구조를 정의할 수 있다. 실제로는 프로토타입 기반 상속을 감추고 있지만, 개발자에게는 전통적인 객체 지향 프로그래밍의 장점을 제공한다.
- Dog 클래스는 extends Animal을 통해 Animal 클래스를 상속받는다.
- 이를통해 Dog 클래스에서 Animal 클래스의 프로토타입을 사용할 수 있다.
- super는 메소드 오버라이딩 시 부모 클래스의 기능을 유지하거나 확장하는 데 사용할수 있다.