본문 바로가기

Programming Language/Javascript

[강의노트][드림코딩] Class & Object

드림코딩 자바스크립트 클래스 & 오브젝트 강의 노트

 


/Class는 연관 있는 데이터(fields & methods)를 한데 그룹화 - 상속과 다양성이 일어날 수 있음 = 객체지향 언어

class person{
  name; // 속성(field)
  age;
  speak(); /// 행동(method)
}

Object-oriented programing
Class는 붕어빵 틀 - template, 청사진
Object는 instance of class
Syntactical sugar over prototype-based inheritance
Declare once 한번만 선언
No data in 메모리에 올라가지 않음

Class에 data를 넣으면 Object
Can be created many times
메모리에 올라감

1. Class declaration
class Person {
    //constructor
    constructor(name, age){
    //fields
    this.name = name;
    this.age = age;
    }
    //methods
    speak(){
        console.log(`${this.name} : hello`)
    }
}

const a = new Person("Leo", 33);
console.log(a);
console.log(a.name);
console.log(a.age);
a.speak();
console.log(typeof a);
console.log(typeof Person);

2. Getter & setter ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
class User {
    constructor(firstname, lastname, age){
        this.firstname = firstname,
        this.lastname = lastname,
        this.age = age
    }
    get age(){
        return this._age; //무한loop 방지를 위해서 변수에 _ 추가
    }
    set age(value){
        // if(value<0){
        //     throw Error('age cannot be negative');
        // }
        this._age = value < 0 ? 0 : value;
    }
}
const user1 = new User('Steve', 'Jobs', -3)
console.log(user1);

3. Fields (public & private) - constructor 없이 class 생성 가능
class Experiment{
    publicField = 2;
    #privateField = 0; // 외부에서 undefined
}
const exp = new Experiment();
console.log(exp);

4. Static properties and methods
class Article{
    static publisher = "DreamCoding"; // Object에 할당되지 않고 Class 자체에 속함
    constructor(articleNumber){
        this.articleNumber = articleNumber;
    }
    static printPublisher(){
        console.log(Article.publisher);
    }
}

const article1 = new Article(1);
console.log(article1);
console.log(article1.articleNumber);
console.log(Article.publisher);
console.log(Article.printPublisher);
Article.printPublisher();


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 of`);
    }
    getArea(){
        return this.width*this.height;
    }
}


class Rectangle extends Shape {} // Shape의 fields 및 methods 가져옴
class Triangle extends Rectangle {
    draw(){
        super.draw(); // 부모 함수 가져옴
        console.log('❤️') // 자체 함수 추가 정의 가져옴
    }
    getArea(){
        return this.width*this.height/2;
    }
}// Rectangle의 fields 및 methods 가져옴, overriding으로 필요한 부분만 재정의


const shape = new Shape(10, 10, 'red');
const rectangle = new Rectangle(20, 20, 'blue');
const triangle = new Triangle(8,8,'yellow');

console.log(shape);
console.log(rectangle);
console.log(triangle);

shape.draw();
rectangle.draw();
triangle.draw();

console.log(shape.getArea());
console.log(rectangle.getArea());
console.log(triangle.getArea());


6. Class checking: instanceOf
console.log(rectangle instanceof Rectangle);
console.log(rectangle instanceof Shape); // 부모 속성 사용한 것도 true
console.log(rectangle instanceof Triangle);
console.log(rectangle instanceof Object); // 자바스크립트에서 만드는 모든 object는 Object를 상속함 >>> Object 의 공통 methods 사용 가능
console.log(rectangle.toString());
console.log(rectangle.hasOwnproperty);