본문 바로가기

자바스크립트/함수

[자바스크립트] - 객체 생성자 함수

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

(퍼블리셔보다는 프론트앤드가 사용)
내장객체를 생성할 때는 이미 자바스크립트 엔진에 내장되어 있는 객체 생성자 함수를 사용해서 객체를 생성한다. const 변수를 사용하면 재선언, 재할당이 안되니깐 더 안전하다.


중요한 내용이면 const를 쓰자. 

여기서 this 키워드는 생성한 함수, 생성된 객체를 가리킴
객체 생성자 함수의 이름의 첫글자는 대문자로 쓰는 것이 관례이다.(오류가 나진 않는다)

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

let 참조변수 = new 함수명(); -> 객체 생성자 함수 호출문

혹은 간단하게 사용하고 싶다면,
let 참조변수 = {
속성:새 값;,
함수명:function(){...}
}

 

예제실습) 평균몸무게 구해주는-

 
      function CheckWeight(
        name = "이름을 입력해주세요",
        height = 0,
        weight = 0
      ) {
        //사용자의 이름을 this(객체)의 userName속성에 할당함.
        this.userName = name;
        this.userHeight = height;
        this.userWeight = weight;
        this.minWeight;
        this.maxWeight;
        // 사용자의 정보를 단순 출력해주는 함수
        this.getInfo = function () {
          let str = "";
          str += "이름 : " + this.userName + ",";
          str += "키 : " + this.userHeight + ",";
          str += "체중 : " + this.userWeight;

          return str;
        };

        //평균 몸무게 체중을 구해주는 함수
        this.getResult = function () {
          //평균체중의 오차범위
          this.minWeight = (this.userHeight - 100) * 0.9 - 5; //평균체중 -5kg 오차범위까지 포함시킴
          this.maxWeight = (this.userHeight - 100) * 0.9 + 5;

          if (
            this.userWeight >= this.minWeight &&
            this.userWeight <= this.maxWeight
          ) {
            return "정상 체중 입니다";
          } else if (this.userWeight < this.minWeight) {
            return "저체중입니다.";
          } else {
            return "과체중입니다.";
          }
        };
      }

      let kimName = new CheckWeight("김땡땡", 175, 65);
      console.log(kimName);
      console.log(kimName.getInfo());
      console.log(kimName.getResult());

      let parkName = new CheckWeight("박땡땡", 167, 54);
      console.log(parkName); //parkName에 있는 모든 정보를 출력
      console.log(parkName.getInfo(), parkName.getResult());
 
let kimName = new CheckWeight("김땡땡", 175, 65);
      console.log(kimName);
      console.log(kimName.getInfo());
      console.log(kimName.getResult());

let parkName = new CheckWeight("박땡땡", 167, 54);
      console.log(parkName); //parkName에 있는 모든 정보를 출력
      console.log(parkName.getInfo(), parkName.getResult());

위의 애들이 객체 생성 한 것.  kimName과 parkName이라는 객체를 생성