javascript- 클래스

현우.·2024년 6월 13일

JavaScript

목록 보기
6/31
post-thumbnail

대부분의 객체 지향 프로그래밍 언어는 클래스 기반이지만 자바스크립트는 프로토타입을 기반으로 프로그래밍을 한다.
그러나 ES6부터는 자바스크립트 또한 클래스 기반으로 해서 객체지향 프로그래밍을 할 수 있게 되었다.

클래스

객체를 생성할 수 있는 템플릿이다.

  • 객체를 생성할 수 있는 템플릿에는 생성자 함수도 있지만 이는 오래된 방법이다.

인스턴스

클래스를 이용해서 만들어진 객체

코드 📄

  class Person{
    constructor(name){
        this.name = name; 
    }

    introduce = function(){  // introduce(){...}
        return 'My name is ' + this.name;
    }
   }
  // person1,2객체는 Person 클래스의 인스턴스
  let person1 =new Person('khw');
  let person2 =new Person('kar');
  • constructor는 class로 생성된 객체 초기화를 위한 메소드로 한개만 존재한다.
  • 메소드는 보통 생성자 함수 밖에서 작성한다.

함수선언과 클래스 선언의 차이

함수 선언은 호이스팅에 의해 호출하기전에 선언할 수 있지만 클래스는 반드시 선언을 하고 호출을 해야한다.

코드 📄

const c = new Hello(); 
//ReferenceError: Cannot access 'Hello' before initialization

class Hello{}; 

인스턴스 레벨의 프로퍼티,메소드

클래스 안에 있는 constructor의 프로퍼티와 메소드는 인스턴스에 전달된다.
이러한 프로파티와 메소드들을 인스턴스 레벨에 있다고 한다.

클래스 레벨의 프로퍼티,메소드

클래스에서 공통적으로 사용하는 프로퍼티, 메소드를 위해 프로퍼티와 메소드 앞에 static을 붙여주며 정적 프로퍼티, 메소드라고도 한다.
이러한 프로퍼티와 메소드들을 클래스 레벨에 있다고 한다.

코드 📄


  class Person{
    static MAX_PERSONS = 10;  // static  프로퍼티

    constructor(name){
        // 인스턴스 레벨의 프로퍼티
        this.name = name; 
    }
    introduce = function(){
        return 'My name is ' + this.name;
    }
	static addPerson=function(){ // static 	메소드
        return new Person('kwg');
    }
   }

   const person3 =Person.addPerson();
	//Person { introduce: [Function: introduce], name: 'kwg' }
   console.log(person3);
  • 클래스 레벨의 프로퍼티와 메소드는 this를 참조할 수 없다.
    왜냐하면 인스턴스로 전달되지 않고 클래스만이 가지고 있기 때문이다.

필드

class 안에 있는 프로퍼티들을 필드라고 부른다.

코드 📄

class Person{
    //필드
    name;
    sex="male";
    constructor(name){
        this.name = name; 
    }
    // 메소드는 보통 생성자 함수 밖에서 작성
    introduce = function(){
        return 'My name is ' + this.name;
    
    }
   }
   
   let person1 =new Person('khw');
	console.log(person1);
// Person { name: 'khw', sex: 'male', introduce: [Function: introduce] }
  • class안에서 자체적으로 필드를 생성할 수 있다.
  • class안의 필드들은 인스턴스로 전달된다.

접근 제어자

public(기본)

전달된 필드들을 인스턴스가 자체적으로 수정할 수 있다.

코드 📄

person1.name= 'kar';
console.log(person1);
//Person { name: 'kar', sex: 'male', introduce: [Function: introduce] }

#(private)

# 접근 제어자를 이용해 외부에서 접근 불가하게 할 수 있다.

코드 📄

class Person{
    //필드
    #name;
    #sex="male";
    constructor(name){
        this.#name = name; 
    }
    // 메소드는 보통 생성자 함수 밖에서 작성
    introduce = function(){
        return 'My name is ' + this.#name;
    }
   }
  
   let person1 =new Person('khw');
 person1.#name = "kar"; // error.
   person1.#sex = "female"; // error
  console.log(person1);
// Person { introduce: [Function: introduce] }
  • name, sex가 클래스 내부에서만 접근가능하기 때문에 인스턴스를 생성하더라도 필드들은 전달받지 못함을 알 수 있다.
  • private field는 반드시 사용전에 선언되어야 한다.

접근자 프로퍼티 setter, getter

메소드는 특정한 행동(일)을 수행하기위해 사용된다.
그러나 단순히 프로퍼티들을 조합하는것들은 메소드 보다는 프로퍼티에 가깝다.
get,set을 쓰면 메소드지만 프로퍼티처럼 접근할 수 있다.

코드 📄

class Person{
    constructor(name,age){
        this.name = name;
        this.age =age; 
    }
    
    get introduce(){  // introduce함수를 가져온다.
        return `My name is ${this.name} ${this.age}`;
    }
 
    set introduce(name){ // introdcue 함수를 할당한다.
        this.name=name;
    }
   }
    let person1 =new Person('khw',25);
	console.log(person1);
	//Person { name: 'khw', age: 25 }
	console.log(person1.introduce);  // get
	// 	My name is khw 25
   person1.introduce = "kar"; // set
   console.log(person1); 
   // Person { name: 'kar', age: 25 }
  • get은 프러퍼티들을 가져와 조합해 반환할때 사용한다.
  • set은 프로퍼티의 값을 새롭게 할당할 때 사용한다.

상속

공통된 프로퍼티와 메서드를 가진 클래스를 여러개 만들어야 한다면 중복의 문제가 생긴다.

이를 해결 하기 위해 공통된 프로퍼티와 메서드를 가진 부모 클래스를 만들고 상속하는 방법이 있다.

부모 클래스 생성
코드 📄

class Person{
    constructor(name){
        this.name= name;
    }
    talk(){
        console.log("말한다.")
    }
    think(){
        console.log("생각한다.");
    }
};

부모 클래스를 상속하는 자식 클래스 생성1
코드 📄

class White extends Person {
    
  	angle=()=>{
      console.log("뭐든 각지다.")
              }
}
const white = new White('백인');
console.log(white);
//White { name: '백인', angle: [Function: angle] }

// 부모 클래스의 메소드 사용 가능
white.talk(); // 말한다.
white.think(); // 생각한다.

// 자식 클래스에서 직접 만든 메소드
white.angle(); // 뭐든 각지다.

부모 클래스를 상속하는 자식 클래스 생성2
코드 📄

class Black extends Person {
    constructor(name,owner){
      // 상속하고 있는 부모 class의 생성자 함수에 name 전달
        super(name); 
        this.owner =owner;
    }
  
    big=function(){
        console.log("뭐든 크다.");
    }
    //오버라이딩
    think(){
        super.think(); // 부모 class의 think() 메소드 호출
        console.log("흑인이 생각?")
    }
}

const black = new Black('흑인',"백인"); 
//Black { name: '흑인', big: [Function: big], owner: '백인' }
console.log(black);
black.talk(); // 말한다.
black.think(); //생각한다. 흑인이 생각?
black.big(); // 뭐든 크다.
  • super 키워드는 부모가 가지고 있는 메소드를 호출할 때 사용한다.
    • 자식 클래스의 constructor에서 this를 사용하기 전에 super()를 반드시 호출해야 함
  • 오버라이딩: 부모 클래스에 있는 메소드를 자식 클래스에 덮어 씌우는 것
profile
학습 기록.

0개의 댓글