[JS]prototype

여리·2023년 4월 11일
0

class의 연장선상으로 prototype에 대해 공부했다.

위 이미지는 class에 대해서 만들어 놓은 예시내용인데
여기서 class에 대한 prototype을 콘솔로 찍어보았다.

읭??!! 뭐가 있네?!

모든 객체는 __proto__라는 숨겨진 속성을 가지며, 이 속성은 객체의 원형이 되는 다른 객체를 참조한다. __proto__
속성은 객체의 생성 시점에 해당 객체의 생성자 함수에 정의된 prototype 속성을 참조합니다. prototype 속성은 해당 생성자 함수로부터 생성된 모든 객체가 상속할 수 있는 속성과 메소드를 포함합니다.

이건 구글링에서 찾아본 내용인데 나같은 초보자에게는 너무나도 어려운 설명이다 ^^;

프로토타입은 '유전자'라고 생각해보면 이해하는데 도움이 된다.
어떠한 객체를 prototype을 콘솔로 찍어보면 객체에 대한 정보를 확인할 수 있다.

한가지를 예로 들어보면

array = [3,6,5,2,8];
//이건 우리가 흔히 볼 수 있는 우리의 배열을 나타낸다.
//하지만 컴퓨터는 이렇게 인식한다.

array = new Array(3,6,5,2,8);

//결국 두 가지의 소스코는 컴퓨터는 같게 인식한다.
//콘솔로 꼭 찍어보는 경험을 해봤으면 좋겠다.

array에 대해서 대부분의 개발을 공부하는 사람이라면 araay.length, array.sort()가 있다는 것을 알고 있을 것이다.

.length, .sort()는 Array라는 object(배열도 type은 object는 기본상식!)에 .length와 sort()라는것이 prototype이라는 것 안에 있다는 것이다.

여기서 다른 객체 프로퍼티를 추가하려면 추가가 가능하다는것인데 class의 연장선으로 내용을 추가해보면

class Caracter{
	constructor(name,age,gender){
	this.name = name
 this.age = age
 this.gender = gender
 }
  //여긴 자식위치
}

const yeori = new Caracter('여리',29,'male)
//일때,

Caracter.prototype.length = 180;
                          //(여기는 부모위치)
//이면
console.log(yeori.length) //180

가 된다는 것이다.
prototype은 상속의 내용이 있다는 점 참고하자.

class의 내부내용은 자식위치에 넣은 내용들이고 새로 변수를 지정한 Caracter.prototype.length는 부모위치에 내용을 넣은 것이기 때문에 이런 상속관계를 이해하고 사용하여야 한다.

chatGPT에게도 문의를 해봤으니 이점은 참고!

ChatGPT(질문내용 : javascript의 prototype에 대해 설명해줘

JavaScript에서 prototype은 객체 지향 프로그래밍에서 상속을 구현하는데 사용되는 개념입니다. 객체를 생성할 때 해당 객체의 원형이 되는 객체를 정의하고, 이를 상속하는 객체는 원형 객체에 정의된 속성과 메소드를 사용할 수 있습니다.
모든 객체는 __proto__라는 숨겨진 속성을 가지며, 이 속성은 객체의 원형이 되는 다른 객체를 참조합니다. __proto__ 속성은 객체의 생성 시점에 해당 객체의 생성자 함수에 정의된 prototype 속성을 참조합니다. prototype 속성은 해당 생성자 함수로부터 생성된 모든 객체가 상속할 수 있는 속성과 메소드를 포함합니다.
예를 들어, 다음은 Person 생성자 함수와 이를 상속하는 Student 생성자 함수를 정의하는 예시 코드입니다.

function Person(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
}
Person.prototype.introduce = function() {
  console.log(`Hi, my name is ${this.name}, I'm ${this.age} years old and ${this.gender}.`);
}
function Student(name, age, gender, major) {
  Person.call(this, name, age, gender);
  this.major = major;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.study = function() {
  console.log(`I'm studying ${this.major}.`);
}
const student1 = new Student("Alice", 20, "female", "Computer Science");
student1.introduce(); // Hi, my name is Alice, I'm 20 years old and female.
student1.study(); // I'm studying Computer Science.
const student2 = new Student("Bob", 25, "male", "Mathematics");
student2.introduce(); // Hi, my name is Bob, I'm 25 years old and male.
student2.study(); // I'm studying Mathematics.

위 예시 코드에서 Person 생성자 함수는 name, age, gender 매개변수를 받아 객체를 생성합니다. 이후 introduce()와 같은 메소드를 Person.prototype에 추가하여, Person 생성자 함수로부터 생성된 모든 객체가 해당 메소드를 상속받을 수 있도록 합니다.
Student 생성자 함수는 Person 생성자 함수를 상속받으며, Person.call() 메소드를 이용해서 name, age, gender 프로퍼티를 상속받은 후, major 프로퍼티를 추가합니다. 이후 Object.create() 메소드를 이용해서 Person.prototype을 상속하며, constructor 속성을 Student로 바꿔줍니다. 마지막으로 study()와 같은 메소드를 Student.prototype에 추가하여, Student 생성자 함수로부터 생성된 객체에서 해당 메소드를 사용할 수 있도록 합니다.
student1과 student2 객체는 각각 Student 생성자 함수로 생성된 객체이며, Student 생성자 함수로부터 상속받은 introduce() 메소드와 study() 메소드를 모두 사용할 수 있습니다. 이러한 상속 구조를 통해 코드의 재사용성과 유지보수성이 증가하며, 객체 지향 프로그래밍의 핵심 개념 중 하나인 상속을 구현할 수 있습니다.
또한, prototype을 이용한 상속 외에도 ES6에서는 class 문법을 이용한 상속 방법을 제공합니다. class 문법을 이용하면 상속 구조를 보다 직관적으로 표현할 수 있으며, 코드 가독성을 높일 수 있습니다. 예를 들어, 위 코드를 class 문법으로 작성하면 다음과 같습니다.

class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
introduce() {
console.log(Hi, my name is ${this.name}, I'm ${this.age} years old and ${this.gender}.);
}
}
class Student extends Person {
constructor(name, age, gender, major) {
super(name, age, gender);
this.major = major;
}
study() {
console.log(I'm studying ${this.major}.);
}
}
const student1 = new Student("Alice", 20, "female", "Computer Science");
student1.introduce(); // Hi, my name is Alice, I'm 20 years old and female.
student1.study(); // I'm studying Computer Science.
const student2 = new Student("Bob", 25, "male", "Mathematics");
student2.introduce(); // Hi, my name is Bob, I'm 25 years old and male.
student2.study(); // I'm studying Mathematics.

class 문법을 이용하면 prototype을 직접 다루지 않아도 됩니다. 대신 상속 구조를 정의하기 위해 extends 키워드를 이용하고, super() 메소드를 이용해서 부모 클래스의 생성자를 호출할 수 있습니다. 또한, 메소드를 정의할 때 function 키워드를 생략하고 메소드 이름과 괄호만으로 메소드를 정의할 수 있습니다.

profile
beckend developer

0개의 댓글