[JS] 클래스

김다빈·2023년 8월 23일
0

자바스크립트

목록 보기
14/36
post-thumbnail

📌 프로토타입 prototype

객체별로 메소드를 각자 추가해도 되지만 메소드의 내용이 동일하다면 비효율적이다.

const heropy = {
  firstName : 'Heropy',
  lastName : 'Park',
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const neo = {
  firstName : 'Neo',
  lastName : 'Anderson',
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

console.log(heropy.getFullName()); //Heropy Park
console.log(neo.getFullName()); //Neo Anderson

두 객체에 모두 동일한 메소드를 추가하지 않고 heropy 객체에 추가한 메소드를 neo 객체에서도 사용하려면 call 메소드 를 사용할 수 있다.

console.log(heropy.getFullName.call(neo)); //Neo Anderson
//heropy 객체의 getFullName 메소드를 neo 객체에서 사용할 수 있도록 call메소드 사용

프로토타입 방식 사용

function User(first, last) {
  this.firstName = first;
  this.lastName = last;
}

User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`;
}

const heropy = new User('Heropy', 'Park');
const neo = new User('Neo', 'Anderson');

console.log(heropy.getFullName());
console.log(neo.getFullName());

프로토타입의 메소드를 만들 때는 꼭 일반 함수 형태로 만들어야한다.
화살표 함수 형태로 만들면 내부의 this가 가르키는 게 달라지기 때문


📌 ES6 클래스

기존의 프로토타입 방식을 ES6에서 새롭게 나온 클래스 방식으로 작성할 수 있다.

기존 코드는 위의 #프로토타입 방식 참고

클래스 방식

class User {
  constructor(first, last) {
    this.firstName = first;
    this.lastName = last;
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}
  • 클래스 방식으로 메소드 작성할 때 메소드 이름 앞에 . 붙이지 않고 일반 함수 방식으로 작성한다.

📌 Getter, Setter

클래스 내부에서 get, set 이라는 키워드를 사용해서 메서드를 만들 수 있다.
getter, setter 메서드를 실행할 때는 마치 속성처럼 괄호없이 작성한다.

class User {
  constructor(first, last) {
    this.firstName = first;
    this.lastName = last;
  }
  get fullName() { //getter 방식
    return `${this.firstName} ${this.lastName}`;
  }
  set fullName(value) {
    console.log(value);
  }
}

const heropy = new User('Heropy', 'Park');

console.log(heropy.fullName); //(getter) Heropy Park

heropy.firstName = 'Neo';
console.log(heropy.fullName); //(getter) Neo Park

heropy.fullName = 'Neo Anderson'; //(setter) 값을 할당
console.log(heropy); //Neo Park
//setter를 통해 새로 할당받은 값은 있지만 객체 원본의 속성값을 바꾸진 않음.

getter (값을 조회)

  • 값을 얻어내는 용도의 메서드
  • 일반 객체의 속성처럼 사용 console.log(heropy.fullName);

setter (값을 할당)

  • 할당 연산자를 통해 데이터를 할당 heropy.fullName = 'Neo Anderson';

  • 값을 할당할 때 객체의 속성값을 바꿀 수도 있다.

set fullName(value) {
  console.log(value);
  [this.firstName, this.lastName] = value.split(' ');
  //할당받은 값을 사용해서 객체의 속성값을 변경
}

console.log(heropy); //Neo Anderson

📌 정적 메소드

  • 프로토타입 메소드는 객체(인스턴스)에 붙여서만 사용할 수 있다. (정적 메소드와 대비되는 특징)
  • 정적 메소드는 인스턴스에는 사용할 수 없다.

정적 메소드 작성 방법
static 키워드를 붙여서 메소드 작성

class User {
  constructor(first, last) {
    this.firstName = first;
    this.lastName = last;
  }
  static isUser(user) {
    if (user.firstName && user.lastName) {
      return true;
    }
    return false;
  }
}

const heropy = new User('Heropy', 'Park');
const neo = {
  name : 'Neo',
  age :80
}

console.log(User.isUser(heropy)) //true
console.log(User.isUser(neo)) //false

📌 상속

✅ 예시

//운송수단
class Vehicle {
  constructor(acceleration = 1) {
    this.speed = 0;
    this.acceleration = acceleration;
  }
  accelerate() {
    this.speed += this.acceleration;
  }
  decelerate() {
    if (this.speed <=0 ) {
      console.log('정지 상태!');
       return
    }
    this.speed -= this.acceleration;
  }
}

//자전거
class Bicycle extends Vehicle {
  constructor(price = 100, acceleration) {
    super(acceleration);
    this.price = price;
    this.wheel = 2;
  }
}

//자동차
class Car extends Bicycle {
  constructor(license, price, acceleration) {
    super(price, acceleration);
    this.license = license;
    this.wheel = 4;
  }
  //Overriding (오버라이딩) ; 부모로부터 상속받은 메소드를 재정의 하는 것 (덮어쓰기)
  accelerate() {
    if (!this.license) {
      console.error('무면허!');
      return
    }
    this.speed =+ this.acceleration;
    console.log('가속!', this.speed);
  }
}

//보트
class Boat extends Vehicle {
  constructor(price, acceleration) {
    super(acceleration);
    this.price = price;
    this.motor = 1;
  }
}

✅ 실행

const bicycle = new Bicycle(300, 2);
bicycle.accelerate();
console.log(bicycle);

const carA = new Car(true, 7000, 10);
const carB = new Car(false, 7000, 10);

carA.accelerate();
carB.accelerate();

console.log(carA);
console.log(carB);

const boat = new Boat(10000, 5);
boat.accelerate();
console.log(boat);

📌 instanceof 와 constructor

instanceof

instanceof 키워드 앞 쪽에 있는 데이터가 키워드 뒤 쪽에 있는 클래스의 인스턴스인지를 확인하여 불린형으로 반환

상속 관계 확인 가능⭕

// bicycle 클래스 Bicycle 인스턴스인지?
console.log(bicycle instanceof Bicycle) //true
// bicycle 클래스 Vehicle 인스턴스인지?
console.log(bicycle instanceof Vehicle) //true

console.log(boat instanceof Vehicle) //true
console.log(boat instanceof Bicycle) //false

constructor

인스턴스의 constructor 속성이 특정 클래스와 같은지 비교
(= 해당 인스턴스가 어떤 클래스에서 만들어졌는지 확인)

상속 관계 확인 불가능❌

console.log(bicycle.constructor === Bicycle) //true
console.log(bicycle.constructor === Vehicle) //false

console.log(carA.constructor === Car) //true
console.log(carA.constructor === Vehicle) //false
profile
Hello, World

0개의 댓글

관련 채용 정보