본문 바로가기

[JS] 프로토타입(Prototype)이란?

Min_dev 발행일 : 2023-03-14
반응형

자바스크립트에서 객체를 생성할 때, 다른 언어들과는 다른 방식으로 프로토타입을 이용합니다.

이러한 방식을 "프로토타입 기반 언어"라고 합니다.

 

객체 생성 방법

자바스크립트에서 객체를 생성할 때는 클래스를 정의하지 않습니다. 

대신 생성자 함수를 이용하여 객체를 생성합니다.

예를 들어, 아래와 같은 Person 생성자 함수를 정의할 수 있습니다.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

위 코드에서 Person은 객체를 생성하는 "생성자 함수"입니다.

생성자 함수를 이용하여 객체를 생성할 때는 "new" 키워드를 사용합니다.

 

const person1 = new Person('John', 30);
const person2 = new Person('Jane', 25);

위 코드에서 person1과 person2는 모두 Person 생성자 함수를 이용하여 생성된 객체입니다.

 

 

프로토타입

 

자바스크립트에서 객체를 생성할 때는 생성자 함수의 프로토타입을 상속받습니다.

프로토타입은 생성자 함수의 prototype 프로퍼티에 정의됩니다.

Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}

위 코드에서 Person 생성자 함수의 prototype 프로퍼티에 greet라는 메서드를 정의했습니다.

이제 Person 생성자 함수를 이용하여 객체를 생성하면, 생성된 객체는 Person.prototype에 정의된 프로퍼티와 메서드를 상속받게됩니다.

 

 

상속

자바스크립트에서는 객체 간에 상속을 구현할 수 있습니다.

객체를 생성할 때 생성자 함수의 프로토타입을 상속받기 때문에, 프로토타입 체인을 이용하여 상속 관계를 만들 수 있습니다.

 

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
};

function Student(name, age, grade) {
  Person.call(this, name, age);
  this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

const student1 = new Student('Mike', 18, 'A');
student1.greet(); // Hello, my name is Mike and I'm 18 years old.

위 코드에서 Person 생성자 함수는 이름과 나이를 인자로 받아서 객체를 생성합니다.

Person 생성자 함수의 프로토타입에는 greet 메서드가 정의되어 있습니다.

 

Student 생성자 함수는 Person 생성자 함수를 상속받아 생성되며, 학생의 학년 정보를 추가적으로 인자로 받습니다.

Student 생성자 함수 내부에서는 Person 생성자 함수를 call 메서드를 이용하여 호출합니다.

이를 통해 Student 객체에도 이름과 나이 정보가 추가됩니다.

 

Student 생성자 함수의 프로토타입은 Object.create 메서드를 이용하여 Person 생성자 함수의 프로토타입을 상속받습니다. 

또한, constructor 프로퍼티를 다시 Student로 설정하여 Student 객체를 생성할 때 해당 생성자 함수가 호출되도록 합니다.

 

마지막으로 student1 객체를 생성하고 greet 메서드를 호출합니다. student1은 Student 생성자 함수로부터 생성된 객체이며, 프로토타입 체인을 이용하여 Person 생성자 함수의 프로토타입으로 정의된 greet 메서드를 상속받아 사용할 수 있습니다.

 

결과적으로 "Hello, my name is Mike and I'm 18 years old."라는 메세지가 출력됨을 확인할 수 있습니다.

 

 

 

constructor에 대한 추가 설명

위 코드에서 Student.prototype.constructor = Student;은 Student 생성자 함수가 Student.prototype 객체의 생성자 함수가 되도록 설정하는 부분입니다.

 

Student.prototype 객체는 Person.prototype 객체를 상속받아 생성되었습니다.

따라서 Student.prototype 객체의 생성자 함수는 Person.prototype 객체의 생성자 함수인 Person 생성자 함수가 됩니다.

 

하지만, Student 생성자 함수가 Student.prototype 객체를 상속받아서 만들어졌기 때문에, Student.prototype 객체의 생성자 함수를 Student 생성자 함수로 변경해주어야 합니다.

이를 위해서 Student.prototype.constructor 프로퍼티를 Student 생성자 함수로 설정합니다.

 

이제 Student.prototype 객체의 생성자 함수는 Student 생성자 함수가 되었으므로, Student 생성자 함수로부터 생성된 객체들은 Student.prototype 객체와 Student 생성자 함수에 정의된 프로퍼티와 메소드를 사용할 있습니다.

반응형

댓글