[Node.js] 클래스

Cjw.dev·2023년 3월 6일

Node.js

목록 보기
10/10

클래스는 프로토 타입이다.
프로토타입을 깔끔하게 만들어주는 것이 클래스라고 이해하면 된다.
프로토타입 문법을 깔끔하게 작성할 수 있는 Class 문법 도입
Constructor(생성자), Extends(상속) 등을 깔끔하게 처리할 수 있음
코드가 그룹화 되어 가독성이 향상됨.

// 예전에 선언방식

// 생성자 함수
var Human = function(type){
    this.type = type || 'human';
}

// 스태틱 메서드 (생성자 메서드)
Human.isHuman = function(human){
    return human instanceof Human;
}

//프로토타입 메서드(인스턴스 메서드)
Human.prototype.breathe = function(){
    console.log("h-a-a-a-m");
}

var Zero = function(type, firstName, lastName){
    Human.apply(this, arguments);
    this.firstName = firstName;
    this.lastName = lastName;
}
    Zero.prototype = Object.create(Human.prototype);
    Zero.prototype.constructor = Zero // 상속하는 부분
    Zero.prototype.sayName = function(){
        console.log(this.firstName + ' ' + this.lastName);
    };
    var oldZero = new Zero('human', 'Zero', 'Cho');
    Human.isHuman(oldZero); // true
    
// 클래스를 활용한 선언방식

class Human {
    // 생성자 
    constructor(type = 'human'){
        this.type = type;
    }
    // 스태택 메서드
    static isHuman(human) {
    return human instanceof Human
    }

    // 
    breathe() {
        console.log("h-a-a-a-m");
    }
}

class Zero extends Human {
    constructor(type, firstName, lastName){
    super(type);
    this.firstName = firstName; 
    this.lastName = lastName;
    };

    sayName(){
        super.breathe();
        console.log(`${this.firstName} ${this.lastName}`)
    }
}
profile
백엔드 개발 공부 기록 22.11.07 ~ ing

0개의 댓글