본문으로 바로가기

자바스크립트 ProtoType

category JavaScript 2020. 12. 30. 18:35

프로토타입

함수가 생성되는 시점에 같이 생성되는 객체를 프로토타입 객체라고 한다.

프로토타입 객체는 constructor라는 프로퍼티를 가지고 있는 객체이다.

constructor 속성은 자신과 함께 생성된 함수를 가지고있다. (* 재귀형태)

 

생성자함수로 생성된 객체는 자신의 프로토타입으로 생성자함수의 프로토타입 객체를 가지게 된다.

객체의 프로토타입 객체는 브라우저 상에서 __proto__속성을 통해 확인할 수 있다.

객체는 프로토타입 객체가 가지고 있는 프로퍼티는 자신의 것처럼 사용할 수 있다.

프로토타입 객체도 자바스크립트의 객체이기 때문에 일반 객체처럼 동적으로 프로퍼티를 추가할 수 있다.

 

같은 생성자함수로 만들어진 객체들은 같은 프로토타입객체를 가지게 된다. 따라서 해당 프로토타입 객체가

가지고 있는 속성이나, 메서드를 공유해서 사용하게 된다.

 

프로토 타입들의 체인을 프로토체인이라고 한다.

객체의 __proto__속성에 담긴 객체의 __proto__속성에 담긴 객체의 __proto__.....

프로토체인을 통해 연결되 객체들의 속성이나 메서드는 자신의 속성처럼 사용할 수 있다.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    div {
        background-color: skyblue;
        height: 500px;
        border: 1px solid;
    }
</style>
<body>
<div id="proto-note"></div>
<script>
    function Student(className,name,kor,eng,math){
        this.className = className;
        this.name = name;
        this.kor=kor;
        this.eng = eng;
        this.math = math;

        this.getSum = function (){
            return this.kor + this.eng+this.math;
        }

        this.getAvg = function (){
            return this.getSum()/3;
        }

        this.toString = function (){
            return `${this.className} / ${this.name} / 총점 : ${this.getSum()} / 평균 : ${this.getAvg()}`
        }
    }

    let student = new Student('classA','홍길동',100,100,100);
    let student2 = new Student('classB','전우치',100,50,50);
    let student3 = new Student('classC','고길동',100,60,80);

    document.querySelector('#proto-note').innerHTML+=`${student}<br>`
    document.querySelector('#proto-note').innerHTML+=`${student2}<br>`
    document.querySelector('#proto-note').innerHTML+=`${student3}<br>`


    //student의 프로토타입 객체에 academyName 속성을 추가하고 KH로 초기화
    student.__proto__.academyName = 'KH';

    //student, student2, student3의 프로토타입객체 속성이 함께 변한 것을 확인할 수 있다.
    //즉 세 객체가 모두 같은 프로토타입 객체를 __proto__속성으로 바라보고 있음을 확인할 수 있다.
    document.querySelector('#proto-note').innerHTML+=`student 학원명 : ${student.academyName}<br>`;
    document.querySelector('#proto-note').innerHTML+=`student2 학원명 : ${student2.academyName}<br>`;
    document.querySelector('#proto-note').innerHTML+=`student3 학원명 : ${student3.academyName}<br>`;

    //함수의 prototype 속성을 통해 프로토타입객체로 접근해 job속성을 추가하고 dev로 초기화
    Student.prototype.job ='dev';
    document.querySelector('#proto-note').innerHTML+=` student job : ${student.job}<br>`
    document.querySelector('#proto-note').innerHTML+=` student2 job : ${student2.job}<br>`
    document.querySelector('#proto-note').innerHTML+=` student3 job : ${student3.job}<br>`
    //세 객체 모두 같은 프로토타입을 __proto__속성으로 바라보고 있기 때문에 세 객체모두 'dev' 값을 가진'job'속성 추가

    //student객체의 job 속성을 '강사'로 변경
    student.job = '강사';
    //student객체의 toString 메서드를 재정의(오버라이딩)
    student.toString = function (){
        return '오버라이딩된 toString()'
    }

    document.querySelector('#proto-note').innerHTML+=`student : ${student.job} / ${student}<br>`
    document.querySelector('#proto-note').innerHTML+=`student2 : ${student2.job} / ${student2}<br>`
    document.querySelector('#proto-note').innerHTML+=`student2 : ${student3.job} / ${student3}<br>`
    //student의 job과 toString()만 변경된 것을 확인
    //객체의 프로토타입 객체가 아니라 객체의 속성을 변경할 경우 객체에 해당 속성이 새롭게 추가되면서
    //객체.속성명으로 속성을 사용할 때 프로토타입객체의 속성이 아닌 자신의 속성이 불려진다.

    Student.prototype.job ='기획자'
    document.querySelector('#proto-note').innerHTML+=`student : ${student.job} / ${student}<br>`
    document.querySelector('#proto-note').innerHTML+=`student2 : ${student2.job} / ${student2}<br>`
    document.querySelector('#proto-note').innerHTML+=`student2 : ${student3.job} / ${student3}<br>`

    student.__proto__.job='seniorDev'
    document.querySelector('#proto-note').innerHTML+=`student : ${student.job} / ${student}<br>`
    document.querySelector('#proto-note').innerHTML+=`student2 : ${student2.job} / ${student2}<br>`
    document.querySelector('#proto-note').innerHTML+=`student2 : ${student3.job} / ${student3}<br>`

</script>


</body>
</html>

'JavaScript' 카테고리의 다른 글

자바스크립트 상속  (1) 2021.01.01
자바스크립트의 객체2  (0) 2020.12.30
자바스크립트의 객체1  (0) 2020.12.30