javascript기초문법-객체 생성자 함수

전은하·2024년 8월 5일

자바스크립트기초

목록 보기
19/23
post-thumbnail

객체 생성자 함수(Object Constructor Function)

내장객체를 생성할때는 이미 자바스크립트 엔진에 내장되어 있는 객체 생성자 함수를 사용해서 객체를 생성한다.

      [기본형]
      function 함수명(매개변수1, 매개변수2...){
       this.속성명 = 새값;
       this.함수명 = function(){
        자바스크립트코드;}
       }

      let 참조변수 = new 함수명(); <- 객체 생성자 함수 호출문
      let 참조변수 = {
      속성:새값, 
      함수명:function(){...}
      }
      안전하게 보관하려면 let자리에 const 키워드를 사용한다.
      
      
      
  function checkWeight(name, height, weight) {
    // 사용자의 이름을 this(객체)의 userName속성에 할당함.
    this.userName = name;
    this.userHeight = height; //사용자의 키
    this.userWeight = weight; //사용자읭 체중
    this.minWeight;
    this.maxWeight;
    //사용자의 정보를 단순 출력해주는 함수
    this.getInfo = () => {
      let str = "";
      str += "이름 :" + this.userName + ",";
      str += "키 : " + this.userHeight + ",";
      str += "체중 :" + this.userWeight + ",";

      return str;
    };
    //평균체중을 구해주는 함수
    this.getResult = () => {
      //평균체중의 오차범위
      this.minWeight = (this.userHeight - 100) * 0.9 - 5; //평균체중 -5kg
      this.maxWeight = (this.userHeight - 100) * 0.9 + 5; //평균체중 +5kg

      if (
        this.userWeight >= this.minWeight &&
        this.userWeight <= this.maxWeight
      ) {
        return "정상 몸무게 입니다.";
      } else if (this.userWeight < this.minWeight) {
        return "정상 몸무게보다 미달입니다.";
      } else {
        return "정상 몸무게보다 초과입니다.";
      }
    };
  }
  

아래 객체를 consol창에 출력해보면

위의 이미지와 같이 출력된 것을 볼 수 있다. 이처럼 CheckWeight라는 객체가 김땡땡안에 들어가있는 것을 볼 수있다.

profile
안녕하세요

0개의 댓글