[JS] 프로토타입

2022. 5. 23. 11:15·Stack/JavaScript

[[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>

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

[JS] 로딩 (로드시 이벤트 설정하기)  (0) 2022.06.13
[JS] sarar  (0) 2022.06.13
[JS] 구조분해 할당  (0) 2022.05.23
[JS] 슬라이더  (0) 2022.05.23
[JS] 클래스 (ES6)  (0) 2022.05.20
'Stack/JavaScript' 카테고리의 다른 글
  • [JS] 로딩 (로드시 이벤트 설정하기)
  • [JS] sarar
  • [JS] 구조분해 할당
  • [JS] 슬라이더
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[JS] 프로토타입
상단으로

티스토리툴바