Object

Namiya·2025년 7월 7일

JavaScript 연습

목록 보기
14/27
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta name="viewport" content="width=device-width">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://meyerweb.com/eric/tools/css/reset/reset.css">
    <title>Object</title>
</head>
<body>
   
    <script>

        // 직사각형을 표현하는 객체를 생성
        var rect = {
            // 속성
            width: 13,
            height: 8,

            // 메서드
            getArea: function () {
                // 직사각형의 넓이를 구해 반환
                // return width * height;
                // this: 메서드에 접근하는 객체를 나타내는 키워드
                return this.width * this.height;
            }
        };

        console.groupCollapsed('Ex-01');

        // 객체의 너비와 높이, 넓이를 출력
        console.log('Width of rect: ' + rect.width);
        console.log('Height of rect: ' + rect.height);
        console.log('Area of rect: ' + rect.getArea());

        console.groupEnd();

    </script>

    <script>

        // 학생을 표현하는 객체를 생성하고, 평균 점수와 등급을 구해 출력

        var student = {
            // 속성(property)
            name: '김철수',
            korean: 92,
            math: 76,
            english: 84,

            average: 0,
            grade: 'F',

            // 메서드
            getAverage: function() {
                // 평균 점수를 구해 average 속성에 대입
                this.average = (this.korean + this.math + this.english) / 3;

                // 평균 점수를 반환
                return this.average;
            },

            getGrade: function () {
                // 등급을 구하려면 평균이 필요하다.
                this.getAverage();

                // 평균 점수에 따라 등급 확인
                if (this.average > 90) this.grade = 'A';
                else if (this.average >= 80) this.grade = 'B';
                else if (this.average >= 70) this.grade = 'C';
                else if (this.average >= 60) this.grade = 'D';
                else this.grade = 'F';

                return this.grade;
            },

            printConsole: function () {
                // 출력하기 전 평균과 등급을 구한다.
                this.getGrade();

                // 학생의 평균 점수와 등급을 출력
                console.log('Name = ' + this.name);
                console.log('Average = ' + this.average);
                console.log('Grade = ' + this.grade);
            }
        };

        console.groupCollapsed('Ex-02');

        // 학생의 평균 점수와 등급을 구해 출력
        student.printConsole();

        console.groupEnd();

    </script>
   
</body>
</html>

0개의 댓글