Javascript/프로토타입 & 클래스

객체 생성자 Prototype

appmaster 2021. 2. 1. 12:08

주로 객체를 선언할때는 대문자부터 시작하고, new라는 키워드를 이용합니다.

function Animal(type, name, sound){
    this.type = type;
    this.name = name;
    this.sound = sound;
    this.say = function(){
        console.log(this.sound);
    }
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

여기서 비효율적인거는, 새로운 Animal을 만들때마다 새로운 함수를 만든다는 겁니다.

함수를 보면 내용이 똑같은걸 알 수 있습니다. sound와 똑같은 데이터를 사용하는데 두번이나 선언하는겁니다.

어차피 say라는 함수는 sound랑 똑같은 기능을 하는 함수이므로 이것을 바깥으로 꺼내서 재사용합니다.

 

 

Prototype사용하기

function Animal(type, name, sound){
    this.type = type;
    this.name = name;
    this.sound = sound;
}

Animal.prototype.say = function(){
    console.log(this.sound);
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

똑같이 출력값이 멍멍, 야옹으로 나옵니다. 

하는 역할은 객체생성자로 무언가를 만들어 냈을때, 그걸로 만들어진 객체끼리 공유할수있는 값이나 함수를 prototype으로 설정할 수 있는것이다.

 

 

 

 

function으로 사용하기

function Animal(type, name, sound){
    this.type = type;
    this.name = name;
    this.sound = sound;
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

function say(){
    console.log(this.sound);
}

dog.say = say;
cat.say = say;

dog.say();
cat.say();

이 prototype이 사용되는방식은 이렇게 모든 Animal에게 이런 공통된 함수를 가질 수 있게 하자는 뜻입니다.