JavaScript 객체 기본 - prototype 과 class

Deong_gu·2022년 3월 27일
0
post-thumbnail

생성자 함수를 공부할 때 프로터티 값이 함수인 즉, 메서드가 존재할 경우, 객체(인스턴스)가 생성될 때마다 호출되면서 내부 메서드를 새롭게 생성함으로써 그만큼의 메모리 낭비를 발생시켜 성능을 떨어지게 된다는 걸 알게되었습니다.

이에 prototype을 이용하여 여러개의 객체가 하나의 함수를 공유하므로써 성능을 높이고 메모리를 절약할 수 있습니다. 유지 보수에 용이한 부분도 있습니다.

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
}
//생성자함수 내의 메소드 단점 보완 (공통으로 사용되는 함수)
//프로토타입
PersonInformation.prototype.testresult = function(){
    return this.score - this.penalty;
}
const devil = new PersonInformation(300,'trouble','red','none','none','devil@hell.devil',80,0);
console.log(devil);
console.log(devil.testresult());

class

객체를 만드는 공장, ES6부터 도입된 문법.
class는 객체의 초기 값을 지정하기 위해서 객체가 생성될 때 실행되기로 약속된 함수가 있습니다. 바로 constructor 함수입니다. 이 함수를 이용해 객체의 초기 값을 설정할 수 있습니다. 자바스크립트는 객체를 생성할때 자동으로 constructor 함수를 호출합니다.

class PersonInformation{
    constructor(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;
    }
    testresult(){
        return this.score - this.penalty;
    }
}
const devil = new PersonInformation(300,'trouble','red','none','none','devil@hell.devil',80,0);
console.log(devil);
console.log('devil.testresult : ', devil.testresult());
profile
프론트엔드 개발자가 되기 위해 공부 중입니다.

0개의 댓글