[JS] 클래스와 인스턴스 정리🧹 (ES5, ES6)

TATA·2023년 1월 13일
0

JavaScript

목록 보기
14/25

✔️ 객체 지향 프로그래밍이란?

하나의 모델이 되는 청사진(설계 도면)을 만들고,
그 청사진을 바탕으로 한 객체를 만드는 프로그래밍 패턴을 말한다.

여기서 청사진을 바탕으로 만든 객체인스턴스라고 부르고
청사진클래스라고 부르면 된다.

❗️참고) 클래스는 알아보기 쉽게 앞글자를 대문자로 적어주어야 합니다.
❗️참고) 메서드 호출 방식을 이용할 때에는 화살표 함수를 쓰지 않습니다.
❗️참고) 화살표 함수는 this, prototype, arguments 정보를 생성하지 않습니다.


🧽 ES5와 ES6 클래스 사용법

ES5 사용법과 ES6 사용법 2가지가 있는데 최근에는 주로 ES6을 많이 사용한다.

ES5 클래스는 함수로 정의할 수 있다.

function Car(brand, name, color) {
  this.brand = brand;
  this.name = name;
  this.color = color;
}

Car.prototype.refuel = function() {
  console.log(this.name + '에 연료를 공급합니다.')
}

Car.prototype.drive = function() {
  console.log(this.name + '가 운전을 시작합니다')
}

ES6에서는 class라는 키워드를 이용해 정의할 수 있다.

class Car {
  constructor(brand, name, color) {
    this.brand = brand;
    this.name = name;
    this.color = color;
  }
  
  refuel() {
    console.log(this.name + '에 연료를 공급합니다.')
  }
  
  drive() {
    console.log(this.name + '가 운전을 시작합니다')
  }
}

❓그럼 어떻게 인스턴스를 사용하나요?

new 키워드를 통해 클래스의 인스턴스를 만들 수 있다.

let avante = new Car('hyundai', 'avante', 'black');
avante.color; // 'black'
avante.drive(); // 아반떼가 운전을 합니다.

let mini = new Car('bmw', 'mini', 'white')
mini.brand; // 'bmw'
mini.refuel(); // 미니에 연료를 공급합니다.

// 각각의 인스턴스는 Car라는 클래스의 고유한 속성과 메소드를 가지게 됩니다.

🧽 ES6 상속 extends

아래는 class extends를 이용해 만든 User가 Car을 상속받는 코드이다.

class User extends Car {
  constructor(brand, name, color, user) {
    super(brand, name, color); // 부모의 속성
    this.user = user;
  }
}

🧽 ES5 상속 call, Object.create

부모 클래스 생성

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.introduce = function () {
  return '제 이름은 ' + this.name + ' 입니다.'
}

자식 클래스 생성
call() : 부모 클래스의 속성을 호출.

// call()은 부모 클래스의 속성을 호출합니다.
function Character(name, age, nickname) {
  Person.call(this, name, age); // 부모클래스.call(this, 매개변수)
  this.nickname = nickname;
}

상속
Object.create() : 부모 프로토타입(prototype)을 참조할 수 있게 해준다.

Character.prototype = Object.create(Person.prototype)
// Person.prototype.constructor가 Character로 대체 됩니다.

Person.prototype.constructor = Person;
// 프로토타입 생성자 바꿔주기

결과

const tata = new Character("taehyung", 29, "tata");
console.log(tata.name); // taehyung
console.log(tata.nickname); // tata
console.log(tata.introduce()); // 제 이름은 taehyung 입니다.

🧽 은닉화 #

아래 코드처럼 단순하게 #을 붙이면 된다.

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

const tata = new Person('tata', 29)
console.log(tata.name) // undefinde

🧽 타입 확인 방법

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

const tata = new Person('tata', 29)

console.log(tata.constructor.name); // Person
console.log(tata instanceof Preson); // true
console.log(tata instanceof Object); // true

// __proto__와 getPrototypeOf로 부모 클래스의 프로토타입,
// 혹은 '부모의 부모 클래스'의 프로토타입을 탐색할 수 있다.
tata.__proto__ // Person
Object.getPrototypeOf(tata) // Person
// __proto__는 비표준 방식이기에
// getPrototypeOf를 쓰는 것을 권장한다.

✔️ 용어 정리

prototype : 모델의 청사진을 만들 때 쓰는 원형 객체이다.
constructor : 클래스 인스턴스를 생성하고 생성한 인스턴스를 초기화하는 역할을 하는 생성자 함수이다.
this : 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context이다.(excution context)
              new 키워드로 인스턴스를 생성했을 때에는, 해당 인스턴스가 바로 this의 값이 된다.

👉 class에서 getter와 setter 사용하는 방법 보러가기

profile
🐾

0개의 댓글