HTML & CSS & JS/JS
[JS] 프로토타입
가자미
2021. 3. 17. 16:47
prototype : 함수를 개체로 선언할 때 함수를 매 인스턴스마다 선언하는게 부담스러워서 생긴 기능.
프로토타입을 사용하면 여러 인스턴스를 만들어도 해당 함수는 하나로 모두 통용된다.
//prototype
function Animal(type, name, sound){//개체 생성자
this.type = type; this.name = name;
this.sound = sound;
/*function say(){
console.log(this.sound);
}*/
}
Animal.prototype.say=function(){
console.log(this.sound);
}//dog.say=say;cat.say=say;와 같은 의미
const dog = new Animal('개','멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');