210316 개발일지(99일차) - Javscript의 Class와 Object 및 상속, Getter와 Setter

고재개발·2021년 3월 15일
0

Javascript Study

목록 보기
1/9

Class와 Object

Javascript에서 class는 ES6부터 생겼다.
Class(붕어빵 틀)를 이용해서 Object(팥 붕어빵, 피자 붕어빵, 크림 붕어빵 등)를 만든다고 생각하면 된다.

< Class 코드 >

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

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

< Class를 활용해서 Object 만들기 >

const gojae = new Person('gojae', 7);

이렇게 만든 Object에 대해 console.log를 찍어서 어떤 결과가 나오는지 확인해보자.

console.log(gojae.name);
console.log(gojae.age);
gojae.speak();

아래와 같이 출력된다.

Object 생성 방법

  1. object literal syntax
const obj1 = {};
  1. object constructor syntax
const obj2 = new Object();

Object만 생성하는 함수 (Class와 비슷)

아래와 같이 반복해서 Object를 만들어낼 때, Class로 만들어도 되지만 함수로 만들어도 된다. (Class는 ES6 이후에 나온 거라서, 이 전에는 아래와 같이 함수로만 만들었겠지?)

이 때, Class 안의 consturctor처럼 this를 활용해서 만드는데, 주석처리한 this 부분은 생략되었다고 보면 이해에 좋다.

const person1 = { name: 'bob', age: 2 };
const person2 = { name: 'steve', age: 3 };
const person3 = { name: 'dave', age: 4 };
const person4 = new Person('elile', 30);
console.log(person4);


function Person(name, age) {
  // this = {};
  this.name = name;
  this.age = age;
  // return this;
}

Inheritance(상속)

javascript에서 상속은 extends 함수를 이용한다.
'super'를 활용해서 부모에 접근 할 수 있다.

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

Getter & Setter

get method는 property를 읽으려고 할 때 실행되고,
set method는 property에 값을 할당하려고 할 때 실행된다.

아래 Class에서 사람의 이름과 나이(age)를 넣어준다.
이 때, 나이에 음수를 넣어버리는 상황을 Class 내부에서 막아주기 위해 set method에서 이를 해결해준다.

※ 여기서 Field 3개는 firstName, lastName, _age 다!

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);
profile
고재개발

0개의 댓글