본문 바로가기

프로그래밍 공부/JavaScript

JavaScript - 생성자 함수 연습문제

속성
이름 삼겹살
무게 100g
가격 1690원
메서드 설명
calculator(<무게>) 무게를 기반으로 가격을 계산

생성자 함수 이름을 Product로 가지고 product.calculate(200)을 입력할 때 3380을 출력하는 생성자 함수를 만들어라

더보기
생성자 함수

function Product(nameweightprice){
     this.name=name;
     this.weight=weight;
     this.price=price;

     this.calculate=function(weight){
          return this.price*(weight/this.weight);
     }
}
let product=new Product('삼겹살'1001690);
alert('가격은 '+product.calculate(Number(prompt('무게 입력')))+'원 입니다.');

프로토타입

function Product(nameweightprice){
     this.name=name;
     this.weight=weight;
     this.price=price;
}

Product.prototype.calculate=function(weight){
     return this.price*(weight/this.weight);
}

let product=new Product('삼겹살'1001690);
alert('가격은 '+product.calculate(Number(prompt('무게 입력')))+'원 입니다.');

클래스

class Product{
     constructor(nameweightprice){
          this.name=name;
          this.weight=weight;
          this.price=price;
     }
     calculate(weight){
          return this.price*(weight/this.weight);
     }
}
const product=new Product('삼겹살'1001690);
alert('가격은 '+product.calculate(Number(prompt('무게 입력')))+'원 입니다.');

생성자 함수 연습문제.html
0.00MB

'프로그래밍 공부 > JavaScript' 카테고리의 다른 글

JavaScript - Object 객체  (0) 2019.12.11
JavaScript - 기본 자료형과 객체의 차이점  (0) 2019.12.11
JavaScript - 상속  (0) 2019.12.10
JavaScript - 캡슐화  (0) 2019.12.10
JavaScript - 계산기  (0) 2019.12.10