클래스 - 객체를 생성하는 템플릿
class Person {
name;
age;
speak();
}
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(`${this.name}: 안녕`);
}
}
class.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 클래스 선언하기
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 메서드
speak() {
console.log(`${this.name}: 안녕~`);
}
}
// 객체 생성
const min = new Person('min', 30);
const green = new Person('green', 25);
console.log(min.name);
console.log(min.age);
min.speak();
green.speak();
// 클래스 상속
// extends를 이용하여 클래스를 상속받음
// 네모, 삼각형, 원을 만들기전 모양이라는 클래스를 생성
// 모양이라는 클래스를 네모, 삼각형, 원이 상속을 받도록 함
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`모양의 색은 ${this.color}로 그린다.`);
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape{
}
class Triangle extends Shape {
// 오버라이딩
// 필요한 함수만 재정의
draw() {
// 슈퍼를 이용하여 부모요소에 있는 메서드도 적용
super.draw();
console.log('삼각형을 그립니다.');
}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle1 = new Triangle(20, 40, 'red');
triangle1.draw();
// instanceof
// a instanceof b a가 b를 이용해서 만들어졌는지
console.log(rectangle instanceof Shape);
console.log(rectangle instanceof Rectangle);
console.log(triangle1 instanceof Shape);
console.log(triangle1 instanceof Rectangle);
console.log(rectangle instanceof Object);
console.log(rectangle);
</script>
</body>
</html>
'Stack > JavaScript' 카테고리의 다른 글
[JS] 동기 / 비동기 / 프로미스 (0) | 2022.06.15 |
---|---|
[JS/JSON] JSON(; JavaScript Object Notaion) (0) | 2022.06.14 |
[JS] 배열 / 객체 / set 복습 (0) | 2022.06.13 |
[JS] 로딩 (로드시 이벤트 설정하기) (0) | 2022.06.13 |
[JS] sarar (0) | 2022.06.13 |