Stack/JavaScript

[JS] 프로토타입

7ingout 2022. 5. 23. 11:15

[[prototype]]

자바스크립트 객체는 [[prototype]]이라는 숨김 프로퍼티를 갖습니다.

이 숨김 프로퍼티가 다른 객체에 대한 참조가 되는데

다른 객체를 참조하는 경우 참조 타입을 프로토타입이라 부릅니다.

 


 

prototype.html

<!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>Document</title>
</head>
<body>
    <script>
        let animal = {
            eats:true,
            say(){
                console.log('안녕하세요');
            }
        };
        let rabbit = {
            jumps: true,
        }
        rabbit.__proto__ = animal;
        console.log(rabbit.jumps);
        console.log(rabbit.eats);
        console.log(rabbit);
        console.log(animal.eats);
        rabbit.say();
        animal.say();

        const car = {
            wheels: 4,
            dirve:function() {
                console.log('drve...');
            }
        }
        const bmw = {
            color: "red",
            navigator: 1,
        }
        bmw.__proto__ = car;
        bmw.dirve();

        // Object.keys(obj)
        // 해당 객체의 키만 배열로 반환(프로토타입의 키는 포함하지 않음)
        let keys = Object.keys(bmw);
        console.log(keys);

        // for in문은 해당객체의 키뿐만 아니라
        // 해당 객체의 프로토타입의 키까지 포함
        // obj.hasOwnProperty(key) 해당객체의 키만 true를 반환
        // 프로토타입의 키는 false 반환
        for(let key in bmw) {
            if(bmw.hasOwnProperty(key)) {
                console.log('o', key);
            } else {
                console.log('x', key);
            }
        }

        // function Car2 (color) {
        //     this.color = color;
        // }
        // ⭐
        const Car2 = function (color) {
            this.color = color;
            // this.wheels = 4;
        }
        const x1 = new Car2("pink");
        const x2 = new Car2("blue");
        console.log(x1);
        console.log(x2);
        Car2.prototype.wheels = 4;   // ⭐
        console.log(x1);
        console.log(x2.wheels);
        console.log(x1 instanceof Car2);
    </script>
</body>
</html>