본문 바로가기
JavaScript/엘리 JavaScript note

Part 6 <Class vs Object>

by 판순퐁 2021. 12. 26.

*class -template, declare once, no data in

*object -instance of a class, created many times, data in 

JavaScript 에서 class는 ES6에서 추가됨
기존의 프로토타입에 기반하여 간편하게 문법만 추가됨

1. 클래스 선언

class Person {

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

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

*object만들기
const ellie = new Person('ellie', 20);
console.log(ellie.name); →ellie
console.log(ellie.age); →20
ellie.speak(); →ellie: 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; ->Error! call stack exceeded
  return this._age;
 }

set age(value) {
  //this.age = value;
  this._age = value < 0 ? 0 : value;

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


3. Fields (public, private)

class Experiment {
 publicField = 2;
 #privateField = 0; 
 }
private은 값을 읽을 수도 변경할 수도 없음

const experiment = new Experiment( );
console.log(experiment.publicField); ->2
console.log(experiment.privateField); -> undefined

4. Static
들어오는 데이터에 상관없이 공통적으로 클래스에서 쓸 수 있는 거라면 static과 static메서드를 이용하는 것이 메모리 사용을 줄일 수 있음

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); -> undefined
console.log(Article.publisher); -> Dream Coding
Article.printPublisher(); -> Dream Coding

5. 상속 Inheritance

class Shape {
  construtor(width, height, color) {
    this.width = width;
    this.height = height;
    this.color = color;
 }

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

getArea(){
 return width * height;
}

class Rectangle extends Shape{}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); -> drawing blue color of


<다형성> 위의 예제 이어서
const triangle = new Triangle(20,20,'red');

console.log(triangle.getArea); -> 200
triangle.draw(); ->drawing red color!
                    ->▲

---------------------------------------------------------------------------------------

class Triangle extends Shape{
 
 //overriding 
 getArea(){
   return (this.width * this.height) / 2;
  }
 
 draw() {
    super.draw(); 
    console.log(' ▲ ');
  }
}

6. instanceOf (true/false) 
왼쪽의 object가 오른쪽 class의 instance인지 아닌지 알려줌
console.log(rectangle instanceof Rectangle); ->t
console.log(rectangle instanceof Shape); ->t
console.log(rectangle instanceof Object); ->t


'JavaScript > 엘리 JavaScript note' 카테고리의 다른 글

Part 8 <Array 개념과 APIs>  (0) 2021.12.26
Part 7 <Object>  (0) 2021.12.26
Part 5 <Functions 함수>  (0) 2021.12.26
Part 4 <연산, 반복문>  (0) 2021.12.25
Part3 <데이터 타입>  (0) 2021.12.25