jsNote 05: 객체지향언어 class, object와 차이점

Jieun·2021년 1월 7일
0

jsNote

목록 보기
5/13

Class (ES6)

  • 붕어빵을 만들 수 있는 틀(template)
  • 틀을 정의해서 한 번만 선언한다.
  • class는 정의만 되어있고 그 안에 data가 들어있지 않고 메모리에 올라가지도 않는다.
  • 프로토타입 베이스 위에 class만 추가된 syntactical sugar(문법적 설탕)
  • class 안에는 속성(fields)과 행동(methods)이 들어있다.

Object

  • class로 만들 수 있는 붕어빵(instance of a class)
  • 크림이라는 data를 넣으면 크림 붕어빵, 팥이라는 data를 넣으면 팥붕어빵

1. Class declaration 클래스 선언

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

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

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



2. Getter and setter

  • 사용자가 class를 잘못 사용해도 방어적으로 쓸 수 있게해주는 것이 getter와 setter이다.
//class = 커피자판기
//number of coffee = integer of coffee
//function = 동전 넣기, 커피 만들기 
//number of coffee의 수를 사용자가 -1로 설정(getter)해도 setter를 이용해 내가 0 이상으로 만들어 줘야함
//사용자가 number of coffee라는 property를 설정하지 못하게 만들도록 private하게 만드는 게 인캡슐레이션(보호)

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

    get age(){
        return this._age;
    }
    //age를 정의하는 순간 getter를 호출
    
    set age(value){
        // if(value<0){
        //     throw Error('age can not be negative');
        // }
        this._age = value < 0 ? 0 : value;
    }
    //set은 값을 설정하기 때문에 value를 받아와야 함
    //setter를 정의하는 순간, 메모리에 값을 할당하는 것이 아니라 setter를 호출
    //그래서 전달 된 value가 무한정 반복되기 때문에 get, set 안의 변수 이름을 다르게 만들어야 함
}

const user1 = new User('Steve', 'Jobs', -1);
console.log(user1.age); //0
  • User class에 선언된 field는 firstname, lastname, _age 3개이다.
  • setter logic : user1이 오브젝트로 선언되면 age 매개변수는 setter에 의해 값이 set 된다. 실행된 setter는 매개변수를 전달받아 this._age에 값을 저장한다.
  • getter logic : console이 실행되면 class에 선언된 getter(호출한 key의 이름과 getter의 이름이 같아야 함)를 실행시킨 후, setter에 저장된 this._age 값을 리턴한다.


3. Fields (public, private)

  • 앞에 해쉬태그를 붙이면 class 내부에서만 접근할 수 있고 값도 변경 가능하다. 외부에서는 읽을 수 없다.
  • 최근에 나와 쓰기에는 무리가 있다. (2020 기준)
class Experiment{
    publicField = 2;
    #privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField); //2
console.log(experiment.privateField); //undefined



4. Static properties and methods

class Article{
    static publisher = 'Coding practice'; //static field 정의

    static printPublisher(){ //static method 정의
        console.log(`print: ${Article.publisher}`);
    }
}

const article1 = new Article();
console.log(article1.publisher); //undefined 
console.log(Article.publisher); //Coding practice 클래스의 이름으로 호출해줘야 값이 나옴
Article.printPublisher(); //print: Coding practice



5. Inheritance 상속과 다양성

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

    //method
    draw(){
        console.log(`drawing ${this.color} color!`);
    }

    //method
    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;
    }
}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); //drawing blue color!
console.log(rectangle.getArea()); //400

const triangle = new Triangle(20, 20, 'Red');
triangle.draw(); //drawing Red color!, 빨간 삼각형 2개 출력
console.log(triangle.getArea()); //200



6. Class checking : instancdof

console.log(rectangle instanceof Rectangle); //ture
//왼쪽 오브젝트가 오른쪽 클래스를 이용해서 만들어졌는지 아닌지 t/f 값으로 출력 
console.log(triangle instanceof Rectangle); //false
console.log(triangle instanceof Shape); //ture
console.log(triangle instanceof Object); //true 
//js에서 만든 모든 클래스는 object를 상속한 것이기 때문에



0개의 댓글

관련 채용 정보