JavaScript 객체 기본 - 생성자 함수(constructor)

Deong_gu·2022년 3월 27일
0
post-thumbnail
//객체 생성
const shin ={
    IQ: 140,
    hobby: 'badminton',
    favoriteColor: 'green',
    weight: '63kg',
    height: '163cm',
    e_mail: 'asdfgg77@naver.com',
    score: 100,
    penalty: 20,
    testresult: function(){
        return this.score - this.penalty;
    } 
}
const god = {
    IQ: 200,
    hobby: 'sacrifice',
    favoriteColor: 'white',
    weight: 'none',
    height: 'none',
    e_mail: 'god@heaven.god',
    score: 100,
    penalty: 20,
    testresult: function(){
        return this.score - this.penalty;
    }
}

이렇게 같은 프로퍼티를 가진 객체가 현재는 두개 존재하지만, 만약 수억 수천개가 존재한다면, 하나하나 타이핑 할 수 있을까? 힘들 것이다...ㅠㅠ ( 개발자 : 살...살려줘..죽...);

이것의 존재는 이를 해결하는 객체 만드는 공장
"생성자 함수"

생성자 함수(constructor)

//생성자함수 생성
function PersonInformation(IQ, hobby, favoriteColor, weight, height, e_mail, score, penalty){
   this.IQ = IQ,
   this.hobby = hobby,
   this.favoriteColor = favoriteColor,
   this.weight = weight,
   this.height = height,
   this.e_mail = e_mail,
   this.score = score,
   this.penalty = penalty,
   this.testresult = function(){
       return this.score - this.penalty;
   }
}

생성자 함수로 객체(인스턴스)를 만들기 위해서는 new 라는 키워드를 사용해야한다.

//인스턴스 생성
const devil = new PersonInformation(300,'trouble','red','none','none','devil@hell.devil',80,0);
console.log(devil);
console.log(devil.testresult());
profile
프론트엔드 개발자가 되기 위해 공부 중입니다.

0개의 댓글