class는 component화 하는곳에 쓰이지 않을뿐이지 쓴다..?
class문법은 캡슐화하는데 도움이 된다!
초기화에는 constructor
클래스의 인스턴스를 만드는데는 new
상속은 extends
와 super
클래스 문법의 예제를 같이 보자!
class Dog {
constructor(name, color) {
this.name = name;
this.color = color;
}
bark() {
console.log("Mang!");
}
}
constructor는 클래스의 새 인스턴스를 만들 때 호출된다.
this는 클래스의 인스턴스를 나타낸다.클래스 정의 내에서 속성과 메서드에 적용된다.
메서드는 클래스 내부에 정의된 함수를 나타낸다.
new를 통해서 클래스의 새로운 인스턴스를 만드려면,
const mango = new Dog ( "Poodle", ivory )
위와 같은 방법으로 만들면 된다.
이번에는 그럼 상속에 대해 알아보자!
상속은 위에서 언급한대로 extends, super를 사용해서 만들 수 있다.
class BigDog extends Dog {
constructor(name, color, kg) {
super(name, color)
this.kg = kg;
}
}
whatKg() {
console.log(`${this.name} Kg is : ${this.kg}`)
}
const myBigDog = new Bigdog('mango','ivory','4')
myBigDog.whatKg() // mango Kg is 4