0. class, object
Class
- template
- declare once
- no data in
- syntactical sugar over prototype-based inheritance
Object
- instance of a class
- created many times
- data in
1. Class declarations
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
speak(){
console.log(`${this.name}:hello!`);
}
}
const cucu = new Person('cucu', 99);
console.log(cucu.age);
console.log(cucu.name);
cucu.speak();
2. getter and setters
get : value return
set : value set
class User{
constructor(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age(){
return this._age;
// .age로 하는 경우 : full stack
}
set age(value){
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('cucu', 'bab', -1);
console.log(user1.age);
3. Fields (public, private)
publicField = 1;
#privateField = 0; -> undefined로 호출
4. Static
static x → class 명으로 호출 (class 자체에 붙어있기 때문)
static 호출 시, undefined
메모리의 사양을 위하여.
5. ☆★상속과 다양성
class Shape{
constructor(width, height, color){
this.width = width;
this.height = height;
this.color = color;
}
draw(){
console.log(`drawing ${this.color} color of`);
}
getArea(){
return this.width *this.height;
}
}
class Rectangle extends Shape{}
class Triangle extends Shape{
getArea(){
return (this.width *this.height)/2;
}}
const rectangle = new Rectangle(20, 10, 'blue');
rectangle.draw();
const triangle = new Triangle(20, 10, 'pink');
triangle.draw();
console.log(rectangle.getArea());
6. instanceOf
return T / F
console.log(triangle instanceof Shape); // shape을 상속했으니 true
console.log(rectangle instanceof Object); // 모든 object class는 Object 상속함 true
'Programming > JavaScript' 카테고리의 다른 글
JS 문법 정리 (6) (0) | 2023.08.24 |
---|---|
JS 문법 정리 (5) (0) | 2023.08.22 |
JS 문법 정리 (3) (1) | 2023.08.15 |
JS 문법 정리 (2) (0) | 2023.08.15 |
JS 문법 정리 (0) | 2023.08.14 |