Javascript/GMA(2302~)

23.04.20 자바스크립트 생성자 함수 및 클래스 - *인스턴스 객체를 생성하고 이를 활용해서 원기둥의 부피 구하기

hyerin1201 2023. 4. 23. 14:59

HTML

<body>
  <div id="container">
    <div id="userinput">
      <form>
        <ul>
          <li>
            <label for="cyl-diameter">지름</label>
            <input type="text" id="cyl-diameter">
          </li>
          <li>
            <label for="cyl-height">높이</label>
            <input type="text" id="cyl-height">
          </li>
          <li>
            <button>계산하기</button>
          </li>
        </ul>
      </form>
    </div>
    <div id="result"></div>
  </div>
</body>

 

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
li {
  list-style: none;
  margin: 15px;
}
li label {
  float: left;
  width: 50px;
  padding: 5px;
}
#container {
  display: flex;
  flex-wrap: wrap;

  justify-content: center;
  align-items: center;
  margin-top: 10px;
}
#userinput {
  width: 320px;
  height: 150px;

  margin-top: 5px;
}
#result {
  border: 1px solid #ccc;
  border-radius: 12px;
  width: 300px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  background-color: #fcfcfc;
}
input[type="text"] {
  width: 140px;
  padding: 5px;
}
button {
  width: 190px;
  margin-left: 5px;
  padding: 5px;
}

 

Javascript

// 생성자 함수 및 클래스를 사용해서 인스턴스 객체를 생성하고 이를 활용해서 원기둥의 부피를 구하는 프로그램
// 원기둥의 부피 : 밑면적 * 높이
// 밑면적 : 파이 * (지름 / 2) * (지름 / 2)

//1.계산하기 버튼에 대한 기능정의
//2.사용자가 입력하는 값에 대한 저장공간
//3.원기둥의 부피를 구하는 계산식..
//4. 결과값을 출력할 공간

// function Cylinder(cylinderDiameter, cylinderHeight) {
//   this.diameter = cylinderDiameter;
//   this.height = cylinderHeight;

//   this.volume = function() {
//     let radius = this.diameter / 2;
//     return(Math.PI * radius * radius * this.height).toFixed(1);
//   };
// };

class Cylinder {
  constructor(cylinderDiameter, cylinderHeight) {
    this.diameter = cylinderDiameter;
    this.height = cylinderHeight;
  }
    volume() {
      let radius = this.diameter / 2;
      return (Math.PI * radius * radius * this.height).toFixed(1);
    };
  };
  
const button = document.querySelector("button");
const result = document.querySelector("#result");

button.addEventListener("click", function(e) {
  e.preventDefault();
  const diameter = document.querySelector("#cyl-diameter").value;
  const height = document.querySelector("#cyl-height").value;

  if(diameter == "" || height == "") {
    result.innerText = `지름과 높이 값을 입력하세요`;
  } else {
    let cylinder = new Cylinder(diameter, height);
    result.innerText = `원기둥의 부피는 ${cylinder.volume()} 입니다.`;
  }
});