자바스크립트 class vs object

chanykim·2021년 7월 24일
0

강의: https://www.youtube.com/watch?v=_DLhUBWsRtw&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=6

클래스는 자체에는 데이터가 들어있지 않고 틀만 정해둔다.(한번만 선언)
실제로 데이터를 넣어 만드는 것이 바로 오브젝트이다.
오브젝트는 클래스를 이용해서 다양한 것들을 만들 수 있다.
예를 들어 붕어빵 틀을 클래스라고 했을 때 (팥, 크림, 피자)붕어빵들이 오브젝트라고 할 수 있다.

Class declarations

class person {
  //constructor
    constructor{name, age}{ //오브젝트를 만들 때 필요한 데이터를 전달한다.
    //fields
    this.name = name;
    this.age = age;
    }
   
    //methods
    speak() {
       console.log(`${this.name}: hello!`);
    }
}

const cadet = new Person('chanykim', 29);
console.log(cadet.name); //chanykim
console.log(cadet.age); //29
cadet.speak(); // chanykim: hello!

Getter and setters

class User {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
  
    get age() { //getter를 정의하는 순간 위에 있는 this.age는 메모리에 올라가있는 데이터를 읽어오는 것이 아니라 이 getter를 호출하게 된다.
        return this._age;
    }
  
    set age(value) { //setter를 정의하는 순간 위에 값을 할당할 때(this.age = age; 여기서 age) 바로 메모리에 할당하는 것이 아니라 이 setter를 호출하게 된다.
        //this.age = value; //이렇게 하면 무한정 setter를 반복하게 되서 call stack size exeeded라는 오류를 나타내게 된다.
        //if (value < 0) {
        //   throw Error('age can not be negative');
        //}
        this._age = value > 0 ? value: 0; //이러한 반복을 없애기 위해 왼쪽과 같이 변수명을 바꿔준다. gettter도 마찬가지.
    }
}

const user = new User('chany', 'kim', -1); //나이를 잘못해서 -1을 넣었을 때
console.log(user.age);

fields (public, private)

class Experiment {
    publicField = 2; //외부접근가능
    #privateField = 0; //#을 붙이면 클래스 내부에서만 값이 보여지는 private 속성이 된다.
}

const experiment = new Experiment();
consol.log(experiment.publicField); // 2
consol.log(experiment.privateField); // undefined

static 속성과 메소드

오브젝트와 상관없이 들어오는 데이터와 상관없이 공통적으로 클래스에서 쓸 수 있는거라면 static과 static methods를 이용해서 작성하는 것이 메모리의 사용을 조금 줄여줄 수 있다.

class  Person {
    static cadet = 'chanykim';
    constructor(name){
        this.name = name;
    }
}

static printCadet(){
    console.log(Person.cadet); // undefined
}
const person1 = new Person('hson');
const person2 = new Person('hyopark');
console.log(person1.name); // undefined
//staic은 오브젝트마다 할당되는게 아니라 클래스 자체에 붙어있다.
console.log(Person.name); // chanykim
Person.printCadet(); // chanykim

상속과 다양성

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 width * this.height;
    }
}

class Rectangle extends Shape {}
class Triangle extends Shape {
    draw() {
      super.draw(); //부모의 draw 호출
        console.log('△');
    }
    getArea() {
        return (width * this.height) / 2;
    }
}

const rectangle = new Rectangle(20, 20, 'black');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20, 20, 'blue');
triangle.draw();
console.log(triangle.getArea());
profile
오늘보다 더 나은 내일

0개의 댓글