[JS] 자바스크립트 class

sumin·2023년 1월 17일
0

💡 드림코딩님 자바스크립트 기초강의를 듣고 정리 및 공부


Class 문법

기본 문법

class Pesrson {
  //constructor
  constructor(name, age) {
    //fields
    this.name = name;
    this.age = age;
  }

  //method
  speak() {
    console.log(`${this.name} : hello!`);
  }
}

//object 생성
const jack = new Pesrson("jack", 20);
console.log(jack); // Pesrson {name: 'jack', age: 20}
jack.speak(); // jack : hello!
  • 클래스를 만들고 new 클래스이름 호출하면 객체가 생성된다.
  • Constructor(생성자) : object를 만들 data를 전달
  • fields : 전달된 data를 할당해 줌

Getter와 Setter

  • Getter와 Setter를 정의할 때, 메소드 앞에 getset을 붙여준다.
class User {
  constructor(firstName, LastName, age) {
    this.firstName = firstName;
    this.LastName = LastName;
    this.age = age;
  }
}
// 나쁜 예시
const badUser = new User("steve", "job", -1);
console.log(badUser.age); // 나이 -1살은 없다
  • 위의 예시처럼 잘못된 값을 출력하는 것을 방지해 주는 것이 getter와 setter이다.
class User {
  constructor(firstName, LastName, age) {
    this.firstName = firstName;
    this.LastName = LastName;
    this.age = age;
  }
  get age() {
    return this.age;
  }
  set age(value) {
    this.age = value
  } 
}

  • getter과 setter를 정의하는 순간 this.age = value가 되고 무한 루프가 되어 error가 발생한다. 이를 막기 위해서는 프로퍼티의 이름이 중복되지 않게 변경해 주어야 한다.
get age() {
    return this._age;
  }
set age(value) {
  this._age = value < 0 ? 0 : value;
} 

Public & Private

class Experiment {
  publickField = 2;
  #privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publickField); // 2
console.log(experiment.privateField); // undefined
  • public(공개) property : 외부에서 접근 가능
  • private(비공개) property : class 내부에서만 사용함 외부에서는 불가능

정적 메서드 (static)

  • 클래스의 이름으로 호출되는 메서드
  • data와 상관없이 공통적으로 class에서 쓸 수 있는 것이라면 static과 static method를 통해 작성하는 것이 메모리 감소에 도움된다.
class Article {
  // Static property
  static publisher = "Coding";

  constructor(articleNumber) {
    this.articleNumber = articleNumber;
  }
  // Static method
  static printPublisher() {
    console.log(Article.publisher);
  }
}

const article = new Article(1);
console.log(article.publisher); // undefined

console.log(Article.publisher); // Coding
Article.printPublisher(); // Coding

클래스 상속(Inheritance)과 다양성

  • 공통된 부분을 상속을 통해 재사용할 수 있다.

extends

  • extends 키워드를 사용하여 다른 클래스에 상속될 수 있다.
  • class 자식 클래스 extends 부모 클래스 {}
class Shape {
  constructor(width, height, color) {
    this.width = width;
    this.height = height;
    this.color = color;
  }

  draw() {
    console.log(`drawing ${this.color} color!`);
  }

  getArea() {
    return this.width * this.height;
  }
}

class Rectangle extends Shape {}

const rectangle = new Rectangle(20, 20, "blue");
console.log(rectangle.width); // 20
rectangle.draw(); // drawing blue color!

super

  • 자식 클래스가 부모 클래스와 같은 이름의 속성을 정의하면 자식 클래스의 값만 호출되기 때문에 super 키워드를 통해 부모 클래스의 메소드를 그대로 가져올 수 있다.
  • super.부모 프로퍼티, super.부모 메서드
class Shape {
  constructor(width, height, color) {
    this.width = width;
    this.height = height;
    this.color = color;
  }

  draw() {
    console.log(`drawing ${this.color} color of`);
  }

  getArea() {
    return this.width * this.height;
  }
}

class Triangle extends Shape {
  draw() {
    super.draw(); // 부모의 값을 그대로 가져올 수 있음
    console.log("새로운 값");
  }
  getArea() {
    return (this.width * this.height) / 2;
  }
}
const triangle = new Triangle(20, 20, "red");
console.log(triangle.getArea()); // 200
console.log(triangle.draw()); // drawing red color! 새로운 값

instanceOf

  • {object} instanceof ClassName : {object}가 ClassName의 인스턴스 인지 확인한다.
  • true와 false를 반환한다.
console.log(rectangle instanceof Rectangle); // true
console.log(triangle instanceof Rectangle); // false
console.log(triangle instanceof Triangle); // true
console.log(triangle instanceof Shape); // true
console.log(triangle instanceof Object); // true
console.log(triangle.toString());

0개의 댓글