Class 객체지향언어

임홍렬·2022년 8월 18일
0

자바스크립트 공부

목록 보기
6/12
post-thumbnail

class : 붕어빵을 만들 수 있는 틀

  • class자체에는 데이터가 들어있지않고, 틀만(tamplate) 정의해 놓는다.(요론 class에는 요론 데이터만 들어올 수 있어 !!)
  • class에 실제로 데이터 값을 넣어서 만든 것이 object

object :

  • class를 통해 굉장히 많이 만들 수 있고, class는 정의만 한 것이라서 실제로 메모리에 올라가지는 않지만 실제로 데이터를 넣은 object는 메모리에 올라가게 된다.

class 선언

class Person {
  // constructor
  constructor(name, age) {
    // fields
    this.name = name;
    this.age = age;
  }
  // methods
  speak() {
    console.log(`${this.name}: hello!`);
  }
}

const ellie = new Person('ellie', 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();

getter와 setter

getter : return하는 곳
seeter : 값을 설정하는 곳

class User {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  get age() {
    return this._age;
  }

  set age(value) {
    // if (value < 0) {
    //   throw Error('age can not be negative');
    // }
    this._age = value < 0 ? 0 : value;
  }
}

const user1 = new User('Steve', 'Job', -1);
console.log(user1.age);

Fields (public, private)

class Experiment {
  publicField = 2;
  #privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);

static 속성과 메소드

  • 데이터에 상관없이 class가 가진 고유한 값과 이런 데이터와 상관없이 동일하게 반복적으로 사용되는 메소드가 있을때 static을 붙이면 object에 상관없이 class자체에 연결되어있다.
class Article {
  static publisher = 'Dream Coding';
  constructor(articleNumber) {
    this.articleNumber = articleNumber;
  }

  static printPublisher() {
    console.log(Article.publisher);
  }
}

const article1 = new Article(1);
const article2 = new Article(2);
console.log(Article.publisher);
Article.printPublisher();

상속과 다양성

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 {}
class Triangle extends Shape {
  draw() {
    super.draw();
    console.log('🔺');
  }
  getArea() {
    return (this.width * this.height) / 2;
  }

  toString() {
    return `Triangle: color: ${this.color}`;
  }
}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20, 20, 'red');
triangle.draw();
console.log(triangle.getArea());

instanceOf

  • class를 이용해서 만들어진 새로운 instance이다.
console.log(rectangle instanceof Rectangle);
console.log(triangle instanceof Rectangle);
console.log(triangle instanceof Triangle);
console.log(triangle instanceof Shape);
console.log(triangle instanceof Object);
console.log(triangle.toString());

let obj = { value: 5 };
function change(value) {
  value.value = 7;
}
change(obj);
console.log(obj);

profile
뜨내기 FE 개발자

0개의 댓글