[ javascript ] 클래스 정의 및 사용 > javascript&jQuery

본문 바로가기

사이트 내 전체검색

javascript&jQuery

[ javascript ] 클래스 정의 및 사용

작성일 21-02-11 03:16

페이지 정보

작성자 웹지기 조회 1,553회 댓글 0건

본문

객체지향 프로그래밍(Object-oriendted programming)

class: template

object: instance of a class

JavaScript classes

 - introduced in ES6

 - syntactical sugar over prototype-based inheritance


js파일 상단에 선언(오류체크)

 'use strict';

 

1. 클래스선언(Class declarations)

class Person {

    //construtor

    constructor(name, age) {

        //fields

        this.name = name;

        this.age = age;

    }


    //methods

    speak() {

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

    }

}


const test = new Person('test', 20);

console.log(test.name);

console.log(test.age);

test.speak();


2. Getter and setters

class user {

    constructor(firstName, lastName, age) {

        this.firstName = firstName;

        this.lastName = lastName;

        this.age = age;

    }


    //getter에서 사용하는 변수를 들어오는 변수와 다르게 설정 age => _age

    //같게 설정할 경우 무한루프

    get age() {

        return this._age;

    }

    //setter에서 사용하는 변수를 들어오는 변수와 다르게 설정 age => _age

    //같게 설정할 경우 무한루프

    set age(value) {

        /*

        0이하의 값을 사용하지 못하게 설정

        if(value<0){

            throw Error('age can not be negative');

        }

        this._age = value;

        */

        this._age = value < 0 ? 0 : value;


    }

}

const user1 = new user('steve', 'jobs', -1);

console.log(user1.age);


3. Fields (public, private)

Too soon!

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes

privateField = 아직지원하지 않는 기능(undefined라고 뜸) - 바벨을 이용

class Experiment {

    publicField = 2;

    #privateField = 0;

}

const experiment = new Experiment();

console.log(experiment.publicField);

console.log(experiment.privateField);


4. 정적속성 매소드(Static properties and methods)

object에 상관없이 공통적으로 클래스에서 사용(메모리의 사용을 줄여준다.)

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

//static publisher 을 사용하면 object에서 사용불가, 클래스에서 사용가능

//publisher(static없이) 을 지우면 object에서 사용사용가능, 클래스에서 사용불가

console.log(article1.publisher);

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() {

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

    }


    getArea() {

        return this.width * this.height;

    }


    toString() {

        return console.log(` width : ${this.width}, height : ${this.height}, color : ${this.color}`);

    }

}


상속과 다양성 (상속을 위해서 extends를 사용해서 부모클래스를 불러온다.)

class Rectangle extends Shape {}

const rectangle = new Rectangle(20,20,'blue');

rectangle.draw();

console.log(rectangle.getArea());


class Triangle extends Shape {

    //오버라이딩

    draw() {

        //부모의 메소드와 오버라이딩 된 메소드를 모두 호출하고 싶다면 super.draw()를 사용

        super.draw();

        console.log('▲');

    }

    //오버라이딩

    getArea() {

        return (this.width * this.height)/2;

    }

}

const triangle = new Triangle(20,20,'red');

triangle.draw();

console.log(triangle.getArea());

console.log(triangle.toString());


6. 클래스 상속 검사(Class checking : instanceOf)

rectangle 가 Rectangle의 클래스를 통해서 만들어진 것인지 확인( true, false )

console.log(rectangle instanceof Rectangle);

console.log(triangle instanceof Rectangle);

console.log(triangle instanceof Triangle);

console.log(triangle instanceof Shape);

console.log(triangle instanceof Object);



추천0

비추천 0

댓글목록

등록된 댓글이 없습니다.

전체 63건 1 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기