본문 바로가기

Node.js

class

1. 클래스

- 프로토타입 문법을 깔끔하게 작성할 수 있는 것

- Constructor(생성장), Extends(상속)등을 깔끔하게 처리해준다.

- 코드가 그룹화되어 가독성이 향상된다.

//프로토타입 문법

//생성자 함수 선언
var Human = function(type){
	this.type = type||'human'
}
//생성자 메서드(스태틱메서드) 선언
Human.isHuman = function(human){
	return human instanceof Human
}
//인스턴스 메서드(프로토타입 메서드) 선언
Human.prototype.breathe = function(){
	alert('h-a-a-a-m')
}

* 프로토타입 문법의 세가지 변수는 하나의 그룹이다.

* 분리되어있는 세가지 변수를 읽기 쉽도록 한 그룹으로 모은 것이 class이다.

//class문법

class Human{
	constructor(type = 'human'){
    	this.type = type
    }
    static isHuman(human){
    	return human instanceof Human
    }
    breathe(){
    	alert('h-a-a-a-m')
    }
}

2. 클래스의 확장

class Zero extends Human{
	constructor(type, firstName, lastName){
    		super(type)
        	this.firstName = firstName
        	this.lastName = lastName
    }
    sayName(){             
    	super.breathe()
        alert(`${this.firstName}${this.lastName}`)
    }
}

const newZero = newZero('human', 'zero')

1)extends

-생성자의 상속

- class A extends B{             //A에 생성자B를 상속(+확장)하여 사용한다.

        constructor(a, b, c){      //매개변수 a, b, c를 이용해 객체의 틀을 생성

              super(a)                  //생성자의 B.a 프로퍼티를 상속

              this.b = b                 //b와 c를 추가

              this.c = c

 

2) constructor( ) { }

-어떤 생성자 객체를 통해 생겨난 인스턴스(instance)인지를 알려주는 역할을 합니다. 즉 생성자 객체를 반환한다.

 

2)super( )

- 생성자 객체의 프로퍼티를 그대로 가져옴.

 

728x90

'Node.js' 카테고리의 다른 글

비동기 : async/await  (0) 2023.06.29
비동기 : Promise  (0) 2023.06.28
구조분해할당  (0) 2023.06.28
화살표함수  (0) 2023.06.28
호출스택  (0) 2023.06.28