본문 바로가기

JS/JavaScript

[JavaScript] 프로토타입

728x90

프로토타입(prototype)
- 자바스크립트의 모든 객체는 프로토타입이라는 객체를 포함
- 모든 객체는 프로토타입으로부터 프로퍼티와 메소드를 상속
- 자바스크립트의 모든 객체는 최소한 하나 이상의 다른 객체로부터 상속을 받음

    const Rucy = new Dog(); // Dog.prototype
                <-------    Dog.prototype // Dog 프로토타입 상속
        Rucy    
                <-------    Object.prototype // 최상위 객체 Object 프로토타입 상속
                                                        (java의 최상위 클래스인 Object 클래스 상속 개념. 템플릿)

 

<!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, age, color) {
            this.name = name; 
            this.age = age;
            this.color = color;
        }

        const Rucy = new Dog('루시', 11, '흰색');
        console.log(`이름 : ${Rucy.name}`);
        console.log(`나이 : ${Rucy.age}`);
        console.log(`색상 : ${Rucy.color}`);
        console.log(Rucy);

        const PPomi = new Dog('뽀미', 5, '흰색');
        console.log(`이름 : ${PPomi.name}`);
        console.log(`나이 : ${PPomi.age}`);
        console.log(`색상 : ${PPomi.color}`);
        console.log(PPomi);

        Rucy.family = '포메';
        Rucy.run = function() { // 루시객체에 직접 프로퍼티메소드를 생성.
            return `${this.name}이 달립니다.`;
        }

        console.log(`루시의 종 : ${Rucy.family}`);
        console.log(Rucy.run());
        console.log(Rucy);

        console.log(`뽀미의 종 : ${Rucy.family}`);
        // console.log(PPomi.run()); // 뽀미는 run()가 존재하지 않음. 에러
        console.log(PPomi);

        console.log('🤤🤤🤤🤤🤤🤤🤤🤤🤤🤤');

        Dog.prototype.eat = function() { // Dog의 프로토타입에 eat()을 추가.
            return `${this.name}이(가) 사료를 맛있게 먹습니다`;
        }

        console.log(Rucy.eat());
        console.log(PPomi.eat());
    </script>
</body>
</html>

728x90