본문 바로가기

JS/JavaScript

[JavaScript] 자바스크립트의 객체

728x90

객체를 만드는 방법

 

1. 리터럴 표기법 ( 객체를 하나 만들 때 사용하는 것이 좋음 )
    
    const 객체명 = {};  // 빈 객체 생성

    const 객체명 = {
        프로퍼티명1 : 값1,
        프로퍼티명2 : 값2,
        ...
        프로퍼티메소드명1: function() {
            ...
        }
    }

✅ 프로퍼티(property)
- 객체내의 변수 또는 함수
- 객체내의 변수는 프로퍼티라고 부르며, 함수는 프로퍼티 메소드라고 부름

 

<!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>프로퍼티</title>
</head>
<body>
    <h2>프로퍼티</h2>
    <script>
        'use strict';
        const user = {
            userid : 'apple',
            name : '김사과',
            gender : '여자',
            age : 20,
            birthday : '20021011',
            memberId : function() {
                return 'korea' + this.birthday;
            }
        }

        console.log(user.userid);
        console.log(user.name);
        console.log(user.gender);
        console.log(user.age);
        console.log(user.birthday);
        console.log(user.memberId); // 함수 형태를 출력
        console.log(user.memberId()); // 함수 실행한 결과 출력

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

 

 

2. 생성자를 이용한 객체 생성 ( 객체를 여러개 만들 때 유용. 코드 재활용 가능 )
- new 연산자를 사용하여 객체를 생성하고 초기화 할 수 있음
- 생성자는 메소드이며, 이 메소드는 새롭게 생성되는 객체를 초기화하는 역할을 함

    function 생성자명(매개변수1, 매개변수2 ..) {
        this.프로퍼티명1 = 값1,
        this.프로퍼티명2 = 값2,
        ...
        this.프로퍼티메소드명1 = function() {
            ...
        }
    }

 

    const 객체명1 = new 생성자명(값1, 값2 ..);
    const 객체명2 = new 생성자명(값1, 값2 ..);
    ..

<!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>생성자</title>
</head>
<body>
    <h2>생성자</h2>
    <script>
        'use strict';
        function Dog(name, color) {
            this.name = name;
            this.color = color;
            this.sleep = function() {
                return `${this.name}이(가) 잠을 잡니다`;
            }
        }

        const Rucy = new Dog('루시', '흰색');
        console.log(Rucy.name);
        console.log(Rucy.color);
        console.log(Rucy.sleep());

        const PPomi = new Dog('뽀미', '흰색'); // 객체 여러개 생성 가능.
        console.log(Rucy.name);
        console.log(Rucy.color);
        console.log(Rucy.sleep());
    </script>
</body>
</html>

 

3. 클래스를 이용한 객체생성(ECMA Script 6 ~)

    const 클래스명 = class {
        constructor(매개변수1, 매개변수2 ..) {
            프로퍼티명1 = 값1;
            프로퍼티명2 = 값2;
            ..
        }
        메소드명(매개변수1, 매개변수2 ..) {

        }
        ..
    }

    const 객체명1 = new 클래스명(값1, 값2 ..);
    const 객체명2 = new 클래스명(값1, 값2 ..);

 

내부적으로는 생성자로 만들어져서 객체를 생성함.

<!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>클래스</title>
</head>
<body>
    <h2>클래스</h2>
    <script>
        'use strict';
        const Dog = class {
            constructor(name, age, color) { // 생성자 역할
                this.name = name;
                this.age = age;
                this.color = color;
            }
            play() {
                return `${this.name}이(가) 즐겁게 놉니다`;
            }
        }
        const Rucy = new Dog('루시', 10, '흰색');
        console.log(Rucy.name);
        console.log(Rucy.age);
        console.log(Rucy.color);
        console.log(Rucy.play());
    </script>
</body>
</html>

 

 

 

 

728x90

'JS > JavaScript' 카테고리의 다른 글

[JavaScript] 자바스크립트의 내장 객체 (Math, String, Date객체)  (0) 2022.05.03
[JavaScript] 프로토타입  (0) 2022.05.03
[JavaScript] 변수의 범위  (0) 2022.04.29
[JavaScript] 함수 만들기  (0) 2022.04.28
[JavaScript] 함수  (0) 2022.04.28