공부/JavaScript

class vs object, class정리 (dreamcoding) | ES6

Dev_YJ 2021. 1. 27. 00:20

CLASS

 - fields + method.
 - data class : method가 없는 class
 - class 자체엔 data가 없고 틀만 있다. template (붕어빵틀)
 - class에 data를 넣으면 object (피자붕어빵)

javaScript에 class가 도입된 것은 ES6부터. prototype-based inheritance

 

1. Class declarations

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

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

const luce = new Person('luce', 20);
console.log(luce.name); //luce
console.log(luce.age); //20
luce.speak(); //luce: hello!

 

2. Getter and Setters

class User {
  constructor(firstName, lastName, age) {//생성자
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  get age() {
    return this._age; //_age 이런식으로 써야 오류x
  }

  set age(value) {
    // if (value < 0) {
    //   throw Error('age can not be negative');
    // }
    this._age = value < 0 ? 0 : value; //if문말고 이런식으로 간단하게
  }
}

const user1 = new User('Steve', 'Job', -1); 
//사용자가 잘못사용(age를 -1로 입력하는등)하더라도 
//조금 방어적으로 만들 수 있게 해주는것이 getter와 setter
console.log(user1.age); //0

 

3. Fields (public, private)

최근에 추가된 것이라 쓰기엔 이르다.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields

class Experiment {
  publicField = 2; //생성자를 쓰지않고 이렇게 정의할 수 있는데 그냥 쓰면 public
  #privateField = 0; //#기호를쓰면 private filed (클래스 외부에서는 값을 읽을수도 변경할수도x)
}
const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);

 

4. Static properties and methods

Too soon! 이것도 쓰기에는 무리가 있음

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(article1.publisher);
//static을 사용하면 object마다 할당되는것이 아니라 class자체에 할당 =>Dream Coding 출력x

console.log(Article.publisher);
Article.printPublisher();
//=>이렇게 class자체를 사용하면 된다

//object에 상관없이 공통적으로 쓸 수 있는거라면 이렇게 쓰는것이 성능면에서 좋다.

 

5. Inheritance 상속

a way for one class to extend another class.

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(); // super을 사용해 상속받은것도 같이 호출가능
    console.log('🔺'); // overiding
  }
  getArea() {
    return (this.width * this.height) / 2; //다형성. 필요한 함수들만 overiding해서 작성하는것
  }

  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());

 

6. Class checking: instanceOf

왼쪽의 object가 오른쪽 class를 이요해 만들어진건지 확인

console.log(rectangle instanceof Rectangle); //t
console.log(triangle instanceof Rectangle); //f
console.log(triangle instanceof Triangle); //t
console.log(triangle instanceof Shape);  //t
console.log(triangle instanceof Object); //t. 
//모든 object는 javascript의 object를 상속받은것 => toString()같은 기본함수 사용가능

 

'공부 > JavaScript' 카테고리의 다른 글

Array (dreamcoding) | ES6  (0) 2021.01.28
object (dreamcoding) | ES6  (0) 2021.01.27
Arrow Function (dreamcoding)| ES6  (0) 2021.01.26
operator, if, for loop ~(dreamcoding) | ES6  (0) 2021.01.25
async, defer / data types ~ (dreamcoding) | ES5+  (0) 2020.12.09