prototype

신동훈·2022년 7월 13일
0

Javascript

목록 보기
8/8

protopype을 기반으로 객체 상속을 구현하여 중복을 제거한다.

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(circle1.gettArea === circle2.getArea); // false

위 예제는 getArea라는 메서드가 중복 생성되고 모든 인스턴스가 중복 소유한다.

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(circle1.getArea === circle2.getArea); // true

Cirle 생성자 함수가 생성한 모든 인스턴스는 자신의 프로토타입의 모든 프로퍼티와 메서드를 상속받는다.

profile
독학 정리

0개의 댓글