- Class
ES6에서 추가된 문법이다.
class는 C++, Java, C#, PHP 등의 다른 프로그래밍 언어에는 있는 기능지만
Javascript에는 없어서 객체생성자를 사용하여 비슷한 작업을 구현했다.
class를 사용하면 객체생성자로 구현했던 코드를 좀 더 깔끔하게 구현할 수 있으며 상속도 훨씬 쉽게 할 수 있다.
class Animal {
constructor(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
say() {
console.log(this.sound);
}
}
console.log(Animal.prototype.say);
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('야옹이', '야옹');
const dog2 = new Dog('뭉뭉이', '뭉뭉');
dog.say();
cat.say();
dog2.say();
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
area() {
return this.height * this.width;
}
};
const rectangle1 = new Rectangle(5,8).area();
console.log(rectangle1);
const rectangle2 = new Rectangle(4,9).area();
console.log(rectangle2);