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();
출력되는 것은
멍멍
야옹
객체생성자 상속받기
예시)
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.prototype = Animal.prototype;
function Cat(name, sound) {
Animal.call(this, "고양이", name, sound);
}
Cat.prototype = Animal.prototype;
const dog = new Dog("멍멍이", "멍멍");
const cat = new Cat("야옹이", "야옹");
dog.say();
cat.say();
Dog와 Cat에 대한 객체 생성자를 만들고,
Animal.call을 호출해 주고 있다. 이 때, 첫번째 인자는 this를 입력해야하며 후에는 Animal 생성자에서 필요로 하는 파라미터를 넣어주어야한다.
그리고 추가적으로 프로토타입 값을 Animal.prototype으로 해주었다.
Dog.prototype = Animal.prototype;
Cat.prototype = Animal.prototype;
class
ES6에서 추가된 문법
예시)
class Animal {
constructor(type, name, sound) {
this.type = type;
this.name = type;
this.sound = sound;
}
say() {
console.log(this.sound);
}
}
const dog = new Animal("개", "강아지", "멍");
const cat = new Animal("고양이", "야옹이", "야옹");
dog.say();
cat.say();
say()라는 함수를 클래스 내부에 선어하였다, 이를 메소드라고 한다.
이렇게 만들면 자동으로 프로토타입으로 등록이 된다.
클래스를 사용할 때 다른 클래스도 쉽게 상속할 수 있다.
예시)
class Animal {
constructor(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
say() {
console.log(this.sound);
}
}
class Dog extends Animal {
constructor(name, sound) {
super("도그", name, sound);
}
}
class Cat extends Animal {
constructor(name, sound) {
super("캣", name, sound);
}
}
const dog = new Dog("멍멍이", "멍멍");
const cat = new Cat("야옹이", "야옹");
dog.say();
cat.say();
상속 키워드는 extends, super() 함수가 상속받은 클래스의 생성자를 가리킨다.