function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
function과의 구분을 위해 주로 대문자로 시작한다. (ex. Animal)
this.변수명=
을 사용해 매개변수를 저장한다. this는 생성자 자신을 가리킨다.
new 키워드를 사용해 객체를 생성한다.
const dog = new Animal("개", "백구", "멍멍");
const cat = new Animal("고양이", "나비", "야옹");
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();
위의 코드를 보면, dog와 cat은 공통적으로 type, name, sound, say 4가지 요소를 갖고있다. 객체를 생성하게 되면 이 네가지 요소를 객체마다 가지게 되는데 이러한 객체가 수백, 수천개가 있다면 메모리에 남는 공간이 없을지도 모른다. 이를 prototype로 해결할 수 있다. 아래는 say함수를 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();
call메서드를 사용하여 상속을 흉내낼 수 있다.
Animal객체를 상속받는 Dog와 Cat객체를 만들 때 call메서드를 사용한다. 또한 Dog 와 Cat 이 Animal을 프로토타입으로 갖는다는 것을 명시해야한다.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function () {
console.log(this.sound);
};
---여기까진 위와 동일 코드
function Dog(name, sound) {
Animal.call(this, "개", name, sound);
}
---Dog 객체 생성자 함수 생성
function Cat(name, sound) {
Animal.call(this, "고양이", name, sound);
}
---Cat 객체 생성자 함수 생성
Dog.prototype = Animal.prototype;
Cat.prototype = Animal.prototype;
---
자식 객체생성자를 생성할때 부모 객체 생성자 명.call( this,부모 객체 생성자의 파라미터들) 을 작성하면 된다. 상속을 흉내내는 것이지만 상속에서 쓰이는 자식-부모의 개념으로 작성했다.
prototype을 공유해야 하기 때문에 Cat, Dog 객체 생성자 함수를 만들고 나서 prototype 값을 Animal.prototype 으로 설정한다. Dog.prototype = Animal.prototype;
클래스를 알고 있다면 프로토타입보다 더 깔끔하고 상속도 편하게 할 수 있다는 것을 알 수 있다. 다음에 클래스에 대해 알아보자