[자바스크립트 문법] 프로토타입(prototype) (추후 작성...)

김형빈·2024년 4월 30일
0

상속과 프로토타입

function Circle(radius){
  	this.radius = radius;
  	this.getArea = function () {
      	return Math.PI * this.radius ** 2;
    };
}

const circle1 = new Circle(1);
const circle2 = new Circle(2);

console.log(circle.getArea === circle2.getArea); // false
console.log(circle1.getArea()); //3.141592.....
console.log(circle2.getArea()); //12.566370...

위 코드의 문제점

  • Circle 생성자 함수는 인스턴스를 생성할 때마다 getArea 메서드를 중복 생성하고 모든 인스턴스가 중복 소유한다.
    • 메모리를 불필요하게 낭비한다.
  • getArea 메서드는 모든 인스턴스가 동일한 내용의 메서드를 사용하므로 단 하나만 생성하여 모든 인스턴스가 공유해서 사용하는 것이 바람직하다.

프로토타입(prototype)을 통한 중복 제거

function Circle(radius){
  	this.radius = radius;
}

Circle.prototype.getArea = function () {
  return Math.PI * this.radius ** 2;
};

const circle1 = new Circle(1);
const circle2 = new Circle(2);

console.log(circle.getArea === circle2.getArea); // false
console.log(circle1.getArea()); //3.141592.....
console.log(circle2.getArea()); //12.566370...
  • getArea 메서드는 단 하나만 생성되어 프로토타입인 Circle.prototyle의 메서드로 할당되어 있다.
  • 따라서 Circle 생성자 함수가 생성하는 모든 인스턴스는 getArea 메서드를 상속받아 사용할 수 있다.

프로토타입 객체

  • 자바스크립트는 프로토타입을 기반으로 상속을 구현한다.
  • 모든 객체는 [[Prototype]]이라는 내부 슬롯을 가지며, 객체가 생성될때 개개체 생성 방식에 따라 프로토타입이 결정되고 [[Prototype]]에 저장된다.
  • 객체와 프로토타입과 생성자 합수는 서로 연결되어있다.

__proto__ 접근자 프로퍼티

  • 자바스크립트는 원칙적으로 내부 슬롯과 내부 메서드에 직접 접근하거나 호출할 수 없다.
  • 모든 객체는 __proto__접근자 프로퍼티를 통해 자신의 프로토타입, 즉 [[prototype]] 내부 슬롯에 간접적으로 접근할 수 있다.
  • _proto__접근자 프로퍼티를 통해 프로토타입에 접근하면 내부적으로 getter 함수인 [[Get]]이 호출되고. 새로운 프로토타입을 할당하면 setter 함수인 [[Set]]이 호출된다.
profile
The secret of getting ahead is getting started.

0개의 댓글