동캄의 코딩도장

JS [Class] 본문

front/HTML&CSS&JS

JS [Class]

동 캄 2022. 1. 24. 00:15

Class
-template
-declare once
-no data in
-틀

Object
- instance of a class
- created many times
- data in

'use strict'

// 1. Class declartions

class person{
    //constructor
    constructor(name,age){
        //fields
        this.name=name;
        this.age=age;
    }
    // methods
    speak(){
        console.log(`${this.name}: hello!`);
    }
}

const ellie = new person('ellie',20);

ellie.speak();

// 2. Getter and Setter

class User{
    constructor(firstName,lastName,age){
        this.firstName=firstName;
        this.lastName=lastName;
        this.age=age;
    }
    get age(){
        return this._age;
    }
    set age(value){
        if (value<0){
            value=0;
        }
    this._age=value<0 ? 0: value;
    }
}

const user1 = new User('Steve','Job',-1);
console.log(user1.age);

// 3. Fields (public, private)

class Experiment{
    publicField=2;
    #privateField=0;
}
const Experiment = new Experiment();
console.log(Experiment.publicField);

// class 밖에서는 private에 접근 불가
// 최근에 나옴

// 4. static properties and methods

class Article{
    static publisher ='Dream Coding';
    constructor(articleNumber){
        this.articleNumber=articleNumber;
    }
    static printPublisher(){
        console.log(Article.publisher);
    }
}

const article1 =new Article(1);
const article2 =new Article(2);
console.log(Article.publisher);
Article.printPublisher();

// 들어오는 값에 상관없이 같은 내용을 출력할 때 사용
// 메모리 사용을 줄일 수 있음

// 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 width * this.height;
    }
}

class Rectangle extends Shape {}
class Triangle extends Shape{
    draw(){
        super.draw();
        console.log('semo');
    }
    // 오버라이딩
    getArea(){
        return this.width * this.height /2;
    }
}
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();
const triangle = new Triangle(20,20,'red');
triangle.draw();
console.log(triangle.getArea());

// 6. Class checking : instanceOf
// 왼쪽의 Object가 오른쪽의 class에 속하는지 확인
console.log(rectangle instanceof Rectangle);

'front > HTML&CSS&JS' 카테고리의 다른 글

JS [array]  (0) 2022.01.24
JS [Object]  (0) 2022.01.24
JS [function]  (0) 2022.01.23
JS [operators]  (0) 2022.01.23
JS [variable]  (0) 2022.01.23