
대부분의 객체 지향 프로그래밍 언어는 클래스 기반이지만 자바스크립트는 프로토타입을 기반으로 프로그래밍을 한다.
그러나 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');
함수 선언은 호이스팅에 의해 호출하기전에 선언할 수 있지만 클래스는 반드시 선언을 하고 호출을 해야한다.
코드 📄
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);
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] }
전달된 필드들을 인스턴스가 자체적으로 수정할 수 있다.
코드 📄
person1.name= 'kar';
console.log(person1);
//Person { name: 'kar', sex: 'male', introduce: [Function: introduce] }
# 접근 제어자를 이용해 외부에서 접근 불가하게 할 수 있다.
코드 📄
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] }
메소드는 특정한 행동(일)을 수행하기위해 사용된다.
그러나 단순히 프로퍼티들을 조합하는것들은 메소드 보다는 프로퍼티에 가깝다.
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 }
공통된 프로퍼티와 메서드를 가진 클래스를 여러개 만들어야 한다면 중복의 문제가 생긴다.
이를 해결 하기 위해 공통된 프로퍼티와 메서드를 가진 부모 클래스를 만들고 상속하는 방법이 있다.
부모 클래스 생성
코드 📄
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(); // 뭐든 크다.