공부공부/JS 딥다이브

[js 딥다이브] 19장 프로토타입

고생쨩 2023. 10. 26. 16:24
728x90

프로토타입

자바스크립트는 프로토타입prototype을 기반으로 상속을 구현한다.


// 생성자 함수
function Circle(radius) {
 this.radius = radius;
}

// Circle 생성자 함수가 생성한 모든 인스턴스가 getArea 메서드를
// 공유해서 사용할 수 있도록 프로토타입에 추가한다.
// 프로토타입은 Circle 생성자 함수의 prototype 프로퍼티에 바인딩되어 있다.
Circle.prototype.getArea = function () {
 return Math.PI * this.radius ** 2;
};

// 인스턴스 생성
const circle1 = new Circle(1);
const circle2 = new Circle(2);

// Circle 생성자 함수가 생성한 모든 인스턴스는 부모 객체의 역할을 하는
// 프로토타입 Circle.prototype으로부터 getArea 메서드를 상속받는다.
// 즉, Circle 생성자 함수가 생성하는 모든 인스턴스는 하나의 getArea 메서드를 공유한다.

console.log(circle1.getArea === circle2.getArea); // true
console.log(circle1.getArea()); // 3.141592653589793
console.log(circle2.getArea()); // 12.566370614359172

String 확장 예제

String.prototype.getWordCount = function () {
 return this.split(' ')
          .filter(function (n) { return n != '' })
          .length;
};

console.log("Stay in the middle".getWordCount()); // 4

프로토타입 메서드 삭제


delete Person.prototype.sayHello;

me.sayHello(); // TypeError: me.sayHello is not a function

프로토타입 교체는 사용하지 않는 편이 좋다.

프로퍼티 열거

const person = {
 name: 'Lee',
 address: 'Seoul',
 __proto__: { age: 20 }
};

console.log(Object.keys(person)); // ["name", "address"]

ES8에서 도입된 Object.values 메서드는 객체 자신의 열거 가능한 프로퍼티 값을 배열로 반환한다.

console.log(Object.values(person)); // ["Lee", "Seoul"]

ES8에서 도입된 Object.entries 메서드는 객체 자신의 열거 가능한 프로퍼티 키와 값의 쌍의 배열을 배열에 담아 반환한다.

console.log(Object.entries(person)); // [["name", "Lee"], ["address", "Seoul"]]
Object.entries(person).forEach(([key, value]) => console.log(key, value));
/*
name Lee
address Seoul
*/

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.