JavaScript

class, object

youngseokim_kr 2021. 12. 20. 18:38

// class 기본

class Person {

    constructor(name,age){
        this.name=name;
        this.age;
    }

//methods
speak() {
    console.log(`${this.name} : hello!`);
    }
}
const kys = new Person('kys',20);
kys.speak();

//getter setter

class User{
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName== lastName;
        this.age=age;
    }

    get age() {
        return this._age;
    }
    set age(value) {
        this._age=value < 0 ? 0 :value;
    }
}

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

//Fields

class Experiment {     //constructor를 쓰지 않고 class 설정
    publicField = 2;     //외부에서 사용 가능
    #privateFeid = 0;     //외부에서 사용 불가능
}

const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);  //출력안됨

//static

class Article {       //들어오는 오브젝트와 상관없이 공통적으로 사용되는것
    static publisher = 'KYS';
    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); //class에 연결되어 있다.
Article.printPublisher();

//Inheritance

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 Retangle extends Shape {}   //draw 함수를 다시 만들면 상속된 draw는 출력이 안된다. 
                                  // super.draw()를 이용해서 둘다 사용 가능 

const rectangle = new Retangle(20,20, 'blue');   //상속을 통해 shape에 선언된 draw를 사용 가능
rectangle.draw();

//class check : instanceOf
console.log(rectangle instanceof Rectangle); t
 
 
 

'JavaScript' 카테고리의 다른 글

배열  (0) 2021.12.20
object  (0) 2021.12.20
js 데이터타입  (0) 2021.12.08
정규 표현식  (0) 2021.10.25
OMDb API  (0) 2021.10.25