Prototype in JS

김보성·2021년 3월 1일
0

JavaScript

목록 보기
8/11

JS에서 prototype??

javascript는 prototype-based language라고 한다.
(모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 prototype object를 가진다는 의미)

prototype object는 상위 prototype object로 부터 속성과 매서드를 상속 받을 수 있고 상위 prototype object도 마찬가지로 상속받을 수 있다. 이를 prototype chain (__proto__) 이라고 한다.

상속되는 매서드와 속성은 각 객체에 저장되는게 아니라 객체의 생성자의 prototype이라는 속성에 정의되어 있다.

prototype이 어디에 쓸까?

예시를 통해 알아보자

function Car(){
  this.wheels = 4;
  this.doors = 4;
}

const tesla = new Car();
const hyundai = new Car();

console.log(tesla.wheels) // 4
console.log(tesla.doors) // 4

console.log(hyundai.wheels) // 4
console.log(hyundai.doors) // 4

이렇게 사용하면 객체를 사용할 때마다 메모리를 많이 잡아먹게 된다. 뜨헉
예를들어서 여기에서는 테슬라와 현대를 객체로 만들었는데, 각각 wheels와 doors로 총 4개의 변수를 할당하게 된다. 0o0

prototype을 사용해보면

function Car(){}

Car.prototype.wheels = 4;
Car.prototype.doors = 4;

const tesla = new Car();
const hyundai = new Car();

결과는 위에 있는 코드와 같다. 이 방법은 어딘가에 있는 Object prototype에 저장해 tesla와 hyundai에서 사용하는 방법이다.

conclusion

콘솔에 찍어보면 쉽게 이해 할 수 있다.
클래스를 만들어서 .__proto__ 를 하게 되면 상위 객체로 object가 있음을 확인 할 수 있다.
그래서 array를 사용할 때 Array.prototype 여기에 속해 있는 array 매소드들을 사용할 수 있다.

profile
Boseong

0개의 댓글