FrontEND/JavaScript
프로토타입
smartlittlepuppy
2023. 4. 16. 19:10
반응형
자바스크립트의 프로토타입이란?
이를 예제로 설명하면, Product라는 객체가 있다고 가정해봅시다. Product 객체는 모든 Product 객체가 공유하는 메서드인 getDiscountPrice를 가지고 있습니다. 이때, Product 객체의 prototype에 getDiscountPrice 메서드를 정의하면, 모든 Product 객체는 해당 메서드를 공유하게 됩니다. 이후, Book 객체를 생성할 때, Product 객체의 prototype을 상속하여 getDiscountPrice 메서드를 사용할 수 있습니다.
function Product(name, price) {
this.name = name;
this.price = price;
}
Product.prototype.getDiscountPrice = function(discount) {
return this.price * (1 - discount);
};
반응형