본문 바로가기

JavaScript/JavaScript기초

[Javascript] 클래스

클래스와 기본문법

클래스(class)란 자바와 같은 객체지향 프로그래밍 언어에서 현실의 개체를 표현하기 위해 사용되는데, 자바스크립트에서도 ES6 부터 class가 도입되었음

 

클래스는 다음과 같이 생성하고 사용할 수 있음

class Person {
	
    constructor(){}
    method{}
    ...
}

let me = new Person();

constructor는 Person 객체를 new 를 사용하여 생성할 때 자동으로 실행되므로 객체를 초기화 할 때 사용됨

 

Person객체 초기화 시 name 추가

class Person {
	
    constructor(name){
    	
        //new로 객체 생성 시 name을 인자로 받아 this.name 을 name으로 초기화
        this.name = name;
    }
    
    getName(){
		return this.name;
	}
}

let me = new Person('ns park');

console.log(me.getName());

 

결과

 

클래스란?

 

클래스는 자바스크립에서 새롭게 생성된 개체가 아니라 사실 함수의 한 종류임

class MyClass{
	
    constructor(){}
    method(){}
}

 

위 클래스에서 함수의 본문은 prototype 의 constructor 에서 가져오고 위의 method 같은 클래스의 메서드 들은 prototype에 프로퍼티로 저장됨

 

// MyClass 와 constructor은 같은 함수
console.log(MyClass === MyClass.prototype.constructor);
//클래스에 정의한 메서드는 prototype에 저장되어 있음
console.dir(MyClass.prototype);

 

결과

 

하지만 클래스가 함수의 한 종류라고 해서 클래스 자체를 함수처럼 호출할 수는 없음

 

클래스로 만든 함수엔 특수 내부 프로퍼티인 [[FunctionKind]]:"classConstructor" 가 저장되고 이 프로퍼티가 존재하는 함수는 new 연산자 없이 실행시킬 수 없음

class Test{
	constructor(){}
}

Test();

 

결과

호출하려면 new 를 사용하라는 오류 발생

이 외에 일반적인 함수와 다른점으로 클래스의 모든 메서드는 enumerable 플래그가 false 이므로 순회 대상에서 제외됨

 

그리고 클래스 내의 코드는 항상 엄격 모드(use strict) 가 적용됨

 

getter / setter

클래스도 객체처럼 getter 와 setter를 사용할 수 있음

class person{
	constructor(){}
    
    get name(){
    	return this._name;
    }
    set name(val){
    	this._name = val 
    }
}

let me = new Person();

me.name = 'son hm';

console.log(me.name);

 

결과

 

클래스의 메서드명 동적 할당

클래스의 메서드 명을 [] 를 사용하여 동적으로 할당할 수 있음

const methodName = 'myMethod';

class Test{
	
    constructor(){}
    [methodName](){console.log(methodName)}
}

let aa = new Test();

console.log(aa.myMethod());

 

결과

 

클래스 필드

클래스 내에서 객체를 생성하는 거와 같이 '프로퍼티' = '값' 형태를 사용하면 어떠한 종류도 클래스에 포함시킬 수 있음

class MyClass{
	name = 'park';
}

let me = new MyClass();

console.log(me.name);

 

결과

 

또한 this를 사용하는 클래스 내의 메서드를 setTimeOut 과 같은 다른 컨텍스트에 넘겨주게 되면 this를 잃어버리는 현상이 발생함

class MyClass{
	constructor(val){
    
    	this.val = val;
    }
    getVal(){ console.log(this.val) }
}

let me = new MyClass(123);

//this를 잃어버려 undefined 가 발생
setTimeout(me.getVal,1000);

 

하지만 클래스 필드 문법을 사용해여 메서드를 선언하면 해당 객체의 this가 유지됨

class MyClass{
	constructor(val){
    
    	this.val = val;
    }
    getVal = () =>{ console.log(this.val) }
}

let me = new MyClass(123);

setTimeout(me.getVal,1000);

 

결과

 

참조: https://ko.javascript.info/class