JavaScript - ES6 Classes

신동환·2022년 6월 8일

js

목록 보기
18/18

Classes

  • 객체 생성을 위한 템플릿, ES5의 클래스 의미와는 다른 문법과 의미를 지닌다
  • 선언과 표현식을 통해 Class를 정의한다
  • Classes는 호이스팅이 적용되지 않고, 일급객체(first-class citizen)이며 strict mode에서 실행된다

Class 선언

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Class 표현식

// unnamed
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// 출력: "Rectangle"

// named
let Rectangle = class Rectangle2 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// 출력: "Rectangle2"

Setters and Getters, Static Methods

  • getter 함수 사용시 주의 사항
    1. 자바스크립트에서는 getter 함수를 사용할때 해당 함수 앞에 get 구문을 명시하여 사용한다
    2. getter의 함수 이름은 숫자나 문자열로 사용가능하다
    3. getter 함수는 매개변수를 가질 수 없다
    4. 같은 이름의 getter 함수를 사용할 수 없다
    5. key-value를 통하여 value 부분에 getter 함수 선언 시 key 이름과 같게 사용할 수 없다

    https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/get

  • setter 함수 사용시 주의 사항
    1. 자바스크립트에서는 setter 함수를 사용할때 해당 함수 앞에 set 구문을 명시하여 사용한다
    2. 위 getter 함수 사용 시 주의 사항에서 2번, 4번, 5번은 setter 함수 사용 시에도 똑같이 적용된다
    3. setter 함수는 최대 한 개의 매개변수만 가질 수 있다

    https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/set

  • Static 메소드(정적 메소드)
    1. 정적 메소드는 클래스의 인스턴스 없이 호출이 가능하다
    1. 정적 메소드 호출 방법
      • 클래스명칭.정적메소드명
      • this.constructor.정적메소드명
      • 인스턴스화된변수명.constructor.정적메소드명

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes/static

Inheritance Between "Classes": Constructor Functions

Inheritance Between "Classes": ES6 Classes

class PsersonCl {
	constructor(fullName, birthYear) {
    	this.fullName = fullName;
        this.birthYear = birthYear;
    }
    
    calcAge() {
    	...
    }
    
    greet() {
    	...
    }
    
    get age() {
    	return ...
    }
    
    set fullName(name) {
    	...
    }
    
    get fullName() {
    	return ...
    }
    
    static hey() {
    	...
    }
}

class StudentCl extends PersonCl {
	constructor(fullName, birthYear, course) {
    	super(fullName, birthYear);
        this.course = course;
    }
    
    introduce() {
    	...
    }
    
    calcAge() {
    	...
    }
}

const martha = new StudentCl('Martha Jones', 2012, 'Computer Science');
martha.introduce();
// StudentCl 클래스에서 재정의 된 calcAge 함수를 호출하게 됨
martha.calcAge();
profile
안녕하세요! Hello, World!

0개의 댓글