Class와 Object 차이

Subin Ryu·2024년 8월 27일

Class

  • 데이터가 안에 없는 틀, 템플릿
  • 한번만 선언한다.
  • ES6부터 도입됨
  • 기존 프로토타입에 기반해 간편하게 사용할 수 있도록 클래스에 대한 문법만 추가 된 것

Object

  • 데이터가 있는 class의 인스턴스
  • 여러번 만들어 진다.

class 사용

  • 기본
class Person {
  //constructor
  constructor(name,age) {
    //fields
    this.name = name;
    this.age = age;
  }
  //methods
  speak(){
    console.log(`${this.name}: hello`);
  }
}
const lucas = new Person('lucas',20);
console.log(lucas.name); // lucas
console.log(lucas.age); // 20
lucas.speak(); // lucas: hello
  • Getter and setter : 말이 되도록 만들어 주는 것
class User{
  constructor(firstname, lastname, age){
  	this.firstName = firstname;
    this.lastName = lastname;
    this.age = age; // this.age는 get age를 호출, age는 set age를 호출
  }
  get age(){
    // this.age가 바로 get age로 전달됨, call stack size exceeded 방지위해 다른 변수이름 사용
    return this._age;
  }
  set age(value){
    // get age의 return값이 set으로 전달됨
    this._age = value < 0 ? 0 : value;
  }
}
const user1 = new User('Steve', 'job', -1);
console.log(user1.age); // 0
  • static properties and methods: 입력에 상관 없이 오브젝트에 모두 공통적인 것일때 메모리 절약위해 static 사용
class Article {
  static pulisher = `lucas`;
  constructor(articleNumber){
    this.articleNumber = articleNumber;
  }
  static printPublisher(){
    console.log(Article.publisher);
  }
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(article1ar.publisher); // undefined 클래스 자체에 있기 때문
console.log(Article.publisher); // lucas
Article.printPublisher(); // lucas

상속과 다형성

class Shape{
  construnctor(width, height, color){
    this.width = width;
    this.height = height;
    this.color = color;
  }
  draw(){
    console.log(`drawing ${this.color} color`);
  }
  getArea(){
    return width * this.height;
  }
}
//Shape에 있는 모든 것들이 Rectangle에 포함됨
class Rectangle extends Shape {}
class Triangle extends Shape {
  // 필요한 함수들은 오버라이딩
  draw() {
    super.draw(); // 부모 함수 호출
    console.log('★')
  }
  getArea(){ 
    return (this.width * this.height) / 2;
  }
}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); // drawing blue color
console.log(rectangle.getArea()); // 400
const triangle = new Triangle(20, 20, 'pink');
triangle.draw(); // drawing pink color
				 // ★
console.log(triangle.getArea()); // 200

//Class checking instanceOf
console.log(rectangle instnaceof Rectangle); //true
console.log(triangle instnaceof Rectangle); // false
console.log(triangle instnaceof Triangle); // true
console.log(triangle instnaceof Shape); // true
console.log(triangle instnaceof Object); // true 자바스크립트의 모든 object는 Object를 상속

더 많은 정보

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

profile
개발블로그입니다.

0개의 댓글