KH/JavaScript

JS_ 사용자 객체(Object) 생성

오늘의 진 2022. 9. 22. 12:31

개발자는 Array, String, Date등 자바스크립트에서 제공하는 코어 객체(내장 객체) 외에 새로운 타입의 객체를 만들어 사용할 수 있다. 

개발자가 선언하는 새로운 객체 타입을 prototype(프로토타입)이라고 부른다. 

 

  • new Object() 로 객체 만들기 

자바스크립트 코어 객체 중 Object 타입을 이용하면 사용자 객체를 만들 수 있다. 

 

 

 


[ 여러가지 방법으로 사용자 객체 생성해보기 ]

new 방법으로 사용자 객체 만들기

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>new Object()로 사용자 객체 만들기</title>
    <script>
        // 메소드로 사용할 3개의 함수 작성
        function inquiry() {
            return this.balance; // 잔금 조회
        }
        function deposit(money) { this.balance += money; } // money 만큼 저금
        function withdraw(money) {
            //예금 인출, money는 인출하고자 하는 액수 
            //money가 balance 보다 작다고 가정 
            this.balance -= money;
            return money;
        }

        //사용자 객체 만들기 
        // 객체를 만들고 객체에 함수를 달아주었다. 
        // 객체의 이러이러한 함수 = 내가 만들어둔 함수 라고 하자 라고 정의함
        //메소드를 매치시킨다 라는 느낌 
        var account = new Object();
        account.owner = "수선화"; // 계좌 주인 프로퍼티 생성 및 초기화
        account.code = "111"; // 코드프로퍼티 생성 및 초기화
        account.balance = 35000; // 잔액 프로퍼티 생성 및 초기화
        account.inquiry = inquiry; // 매소드 작성 
        account.deposit = deposit; // 매소드 작성
        account.withdraw = withdraw; //메소드 작성
    </script>
</head>

<body>
    <h3> new <Object>()로 사용자 객체 만들기</Object></h3>
    <hr>
    <script>
        //객체 활용 
        document.write("account : ");
        document.write(account.owner + ", ");
        document.write(account.code + ", ");
        document.write(account.balance + "<br>");

        account.deposit(10000); // 10000 저금
        document.write("10000원 저금 후 잔액 : " + account.inquiry() + "<br>");

        account.withdraw(5000); // 5000원 인출 
        document.write("5000원 출금 후 잔액 : " + account.inquiry() + "<br>");

    </script>
</body>

</html>

리터럴 방법으로 사용자 객체 생성 

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>리터럴 표기법으로 객체만들기</title>
    <script>
        //사용자 객체 만들기 
        var account = {
            owner: "수선화",
            code: "111",
            balance: 35000,

            inquiry: function () { return this.balance; },
            deposit: function (money) { return this.balance += money; },
            withdraw: function (money) {
                this.balance -= money;
                return money;
            }
        };
    </script>
</head>

<body>
    <h3> 리터럴 표기법으로 사용자 객체 만들기</h3>
    <hr>
    <script>
        document.write("account : ");
        document.write(account.owner + ", ");
        document.write(account.code + ", ");
        document.write(account.balance + "<br>");

        account.deposit(10000); // 10000 저금
        document.write("10000원 저금 후 잔액 : " + account.inquiry() + "<br>");

        account.withdraw(5000); // 5000원 인출 
        document.write("5000원 출금 후 잔액 : " + account.inquiry() + "<br>");
    </script>
</body>
</html>

 

결과는 동일하다. 

 

 

 

 

 

 

 

 

프로토 타입 만들기 (자바와 유사)

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Account 프로토타입 만들기</title>
    <script>
        function Account(owner, code, balance) {
            //프로퍼티 만들기
            this.owner = owner;
            this.code = code;
            this.balance = balance;

            //메소드 만들기 
            this.inquiry = function () { return this.balance; }
            this.deposit = function (money) { return this.balance += money; }
            this.withdraw = function (money) { this.balance -= money; return money; }
        }
    </script>
</head>

<body>
    <h3>Account 프로토타입 만들기</h3>
    <hr>
    <script>
        //new 연산자를 이용하여 계좌 객체 생성 
        var account = new Account("수선화", "111", 35000);

        //객체 활용
        document.write("account : ");
        document.write(account.owner + ", ");
        document.write(account.code + ", ");
        document.write(account.balance + "<br>");

        account.deposit(10000); // 10000 저금
        document.write("10000원 저금 후 잔액 : " + account.inquiry() + "<br>");

        account.withdraw(5000); // 5000원 인출 
        document.write("5000원 출금 후 잔액 : " + account.inquiry() + "<br>");
    </script>
</body>
</html>

 

 


다른 예제들 

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>프로퍼티</title>
    <script>
        //생성자 함수 
        function User(name, age) {
            this.name = name;
            this.age = age;
            this.view = function () {
                document.write('나의 이름은 ' + this.name + '이고 나이는 ' + this.age + "세 입니다. <br>");
            };
        }
        //인스턴스 생성 
        var ob1 = new User('kim', 25);
        var ob2 = new User('lee', 28);
        ob1.view();
        ob2.view();
    </script>
</head>

<body>
    <hr>
    <h2>프로토 타입 Test</h2>
</body>
</html>

 

 

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>book 객체 만들기</title>
</head>

<body>
    <h3>book 객체 만들기</h3>
    <hr>
    <script>
        //book 객체 만들기 
        var book = new Object();
        book.title = "HTML5";
        book.author = "수선화";
        book.price = 20000;
        book.view = function () {
            document.write("book : ");
            document.write(this.title + ", ");
            document.write(this.author + ", ");
            document.write(this.price + "<br>");
        }
        book.view();
    </script>
</body>
</html>

 

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

JS_BOM (Browser Object Model)  (1) 2022.09.26
JS_DOM(Document Object Model)  (1) 2022.09.22
JS_Math , String ,Equality,Identity  (0) 2022.09.22
JS_ Javascript의 객체와 배열  (1) 2022.09.21
JS_숫자 맞추기 게임  (0) 2022.09.21