Js_ Class & 객체(2)

춤추는 병따개·2023년 2월 1일
0
post-thumbnail

Class와 Object

object-oriented programming
class :  template
object : instance of class
Javascript classes
	- introduce ES6
	- syntactical sugar over prototype-based inheritance

Class

클래스는 객체 지향 프로그래밍에서 특정 객체를 생성하기 위해 변수와 메소드를 정의하는 일종의 틀로, 객체를 정의하기 위한 상태(멤버 변수)와 메서드(함수)로 구성된다.

출처: 드림코딩

기초 문법

class MyClass {
  // 여러 메서드를 정의할 수 있음
  constructor() { ... }
  method1() { ... }
  method2() { ... }
  method3() { ... }
  ...
}

클래스를 만들고, new MyClass()를 호출하면 내부에서 정의한 메서드가 들어 있는 객체가 생성됩니다.

객체의 기본 상태를 설정해주는 생성자 메서드 constructor()는 new에 의해 자동으로 호출되므로, 특별한 절차 없이 객체를 초기화 할 수 있습니다.

1️⃣ Class declaration

class person {
    //consteructor생성자
    constructor(name, age) { 
        //fields
        this.name = name;
        this.age = age;
    }
    // methods
    speak() {
        console.log(`${this.name}: hello!`);
    }
}

const ellie = new person('ellie', 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();
//ellie
//20
//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;
    }
//값 설정(때문에 값을 받아와야 함)
    set age(value) {
        // if (value < 0) {
        //     throw Error('age can not be negative');
        // }
        this._age = value < 0 ? 0 : value;
    }          //값이 0보다 작다면?  0을 쓰거나 지정된 값을 쓰겠다.      
}
//사람의 나이는 마이너스(-)가 될 수 없다! get과 set함수는 이 오류를 보완해준다!
const user1 = new User('Steve', 'Job', -5);
console.log(user1.age);

3️⃣ 3. Fields (public, private)

Too soon! 최신 버전이라 아직 사용어렵 // 모질라 사이트 참고

class Experiment {
    publicField = 2;
    #privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField); //2
console.log(experiment.privateField); //undefined

4️⃣ Static properties and mothods

Too soon! 최신 버전이라 아직 사용어렵

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(Article.publisher);
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 method
    draw() {
        console.log(`drawing ${this.color} color of`);
    }
    getArea() {
        return width * this.height;
    }
}

//상속 : extends class 이름
// class에 오버라이팅해서 추가 함수를 작성할 수 있음!!(영상 참고)
class Rectangle extends Shape {}
class Triangle extends Shape {}


const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
//drawing blue color of
const triangle = new Triangle(20, 20, 'red');
triangle.draw();
//drawing red color of

Class checking : instanceOf

console.log(rectangle instanceof Rectangle); // t
console.log(triangle instanceof Rectangle); // f
console.log(triangle instanceof Triangle); // t
console.log(triangle instanceof Shape); // t
console.log(triangle instanceof Object); // t

MDN object 참고페이지 ->

profile
FE 개발 공부 중

0개의 댓글