Stack/JavaScript

[JS] 클래스 (ES6)

7ingout 2022. 5. 20. 11:20

오브젝트

user1 = {

            name:'green',

            age: '32',

            isjob: true,

}

user2 = {

            name:'green',

            age: '32',

            isjob: true,

}

user3 = {

            name:'green',

            age: '32',

            isjob: true,

}

...

생성자함수

function User(name, age, isjob){

            this.name = name;

            this.age = age;

            this.isjob = isjob;

}

let user1 = new User('green', 32, true);

let user2 = new User('blue', 19, false;

let user3 = new User('red', 50, true);

 

class 클래스명 {

            // 생성자

            constructor(name, age){

                        this.name = name;

                        this.age = age;

            }

            speak() {

                        console.log(this.name);

            }

}

let min = new 클래스명('min', 30)

 

* extends 키워드

- 클래수 상속을 사용하면 클래스를 다른 클래스로 확장을 할 수 있습니다.

- 기존에 존재하던 기능을 토대로 새로운 기능을 만들 수 있습니다.

 

* 메서드 오버라이딩

상속받은 클래스의 메서드를 새로운 기능으로 재정의

- 키워드 super를 사용하면 부모클래스에 정의된 메서드 호출가능

- super는 부모 생성자를 호출하는데, 자식 생성자 내에서만 사용할 수 있음

 

* 생성자 오버라이딩

- 상속 클래스의 생성자에겐 반드시 super()를 호출해야합니다.

class Animal {

            constructor(name){

            this.speed = 0;

            this.name = name;

            }

}

class Rabbit extends Animal {

            constructor(name, earLength){

            super(name);

            this.earLength = earlength;

            }            

}

 


 

11class.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 객체는 연관된 속성과 메서드를 묶어서 관리
        // 객체 리터럴
        let person1 = {
            name: '민영',   // 프로퍼티
            age: 32,
            address: '삼산동',
            speak() {   // 메서드(객체가 가지고 있는 함수)
                console.log('금요일이에요 !');
            }
            // speak: function(){   
            //     console.log('금요일이에요 !');
            // }
        }
        console.log(person1.name)
        console.log(person1['age']);
        person1.speak();

        // 생성자 함수
        // function Person(name, age, address) {
        //     // this = {};
        //     this.name = name;
        //     this.age = age;
        //     this.address = address;
        //     this.speak = function() {
        //         console.log('곧 있으면 점심');
        //     }
        //     // return this;
        // }
        // let person2 = new Person('green', 20, '일산동');
        // let person3 = new Person('blue', 22, '일산동');
        // console.log(person1);
        // console.log(person2);

        let person4 = {};
        person4.name = "abc";
        person4.age = 20;
        person4.address = "달동";
        person4.speak = function() {
            console.log('안녕하세요');
        }
        console.log(person4);

        // 클래스를 선언
        class Person {
            // 생성자 함수
            constructor(name, age, address) {
                // fields
                this.name = name;
                this.age = age;
                this.address = address;
            }
            // method 메서드
            speak() {
                console.log('하하하하하하하하하하하하하');
            }
        }
        let person5 = new Person('minmin', 20, '삼산동');
        console.log(person5);
        person5.speak();
    </script>
</body>
</html>

 

12classStudent.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        class Student {
            constructor(name, age, score1, score2) {
                this.name = name;
                this.age = age;
                this.score1 = score1;
                this.score2 = score2;
            }
            // speak() {
            //     console.log('Student 클래스입니다.');
            // }
        }
        const students = [
            new Student('A', 29, 45, 50),
            new Student('B', 30, 60, 70),
            new Student('C', 28, 90, 80),
            new Student('D', 27, 85, 65),
            new Student('E', 32, 80, 90)
        ];
        console.log(students);
        // student.speak();
    </script>
</body>
</html>

 

13extends.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 동물 클래스
        class Animal {
            constructor(name) {
                this.speed = 0;
                this.name = name;
            }
            run(speed) {
                this.speed = speed;
                console.log(`${this.name}은(는) 속도 ${this.speed}로 달립니다.`);
            }
            stop() {
                this.speed = 0;
                console.log(`${this.name}이 멈췄습니다.`);
            }
        }
        //토끼는 동물이므로 동물관련 메서드가 담긴 Animal을 상속받아서 만들기
        class Rabbit extends Animal {
            // 생성자 오보라이딩
            constructor(name, earLength){
                super(name);
                this.earLength = earLength;
            }
            hide() {
                console.log(`${this.name}가 숨었습니다.`)
            }
            // 오버라이딩: 상속받은 부모요소의 메서드와 같은 이름으로 재정의
            // super를 이용하여 부모요소의 메서드도 실행
            stop() {
                super.stop(); 
                this.hide();
            }
        }
        let animal = new Animal('동물');
        animal.run(10);
        animal.stop();
        let rabbit = new Rabbit("흰 토끼", 10);
        console.log(rabbit.name);
        console.log(rabbit.earLength);
        rabbit.run(5);
        rabbit.stop();
        console.log(rabbit);
    </script>
</body>
</html>

 

14class_ex.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        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 {
            //오버라이딩 -  메서드재정의
            getArea() {
                return (this.width * this.height) / 2;
            }
        }
        let rectangle = new Rectangle(20, 20, 'blue');
        let triangle = new Triangle(20, 20, 'red');
        rectangle.draw();
        console.log(rectangle.getArea());
        triangle.draw();
        console.log(triangle.getArea());

        // instanceof
        // a instanceof b a오브젝트가 b클래스를 이용해서 만들어졌는지 체크

        console.log(rectangle instanceof Rectangle);
        console.log(rectangle instanceof Shape);
        console.log(triangle instanceof Triangle);
        console.log(triangle instanceof Shape);
        console.log(triangle instanceof Rectangle);
        console.log(triangle instanceof Object);
        console.log(triangle.toString());
    </script>
</body>
</html>