JavaScript

[JavaScript] Prototype

SangRok Jung 2022. 4. 19. 20:59
반응형

Prototype

개념

  • prototype의 사전적 의미는 “원형"이다. 즉 “원래의 모양”을 뜻한다.
  • 자바스크립트에서 사용하는 거의 모든 데이터는 기본적으로 “객체“(Object type)이다.
  • 객체는 객체마다 기본적으로 가져야 할 기능 및 데이터가 필요하다.
  • 이러한 기능과 데이터를 가진 객체를 prototype이라 하며 자바스크립트에서 특별하게 관리된다.

* prototype는 DNA다.

 

특징

  • 동일한 객체는 동일한 Prototype을 가진다.  즉 아래 a, b는 모두 같은 prototype에서 파생된다.
    <script>
        const a = [1, 2, 3];
        const b = new Array(1, 2, 3);
    </script>
  • Prototype 또한 객체이기 때문에 추가, 변경될 수 있다. 따라서 특정한 객체 타입의 prototype을 변경하면 그 객체 타입 전체가 영향을 받는다.
  • prototype은 호출시 생략할 수 있다.

 

 

 

Prototype을 이용한 상속

prototype은 객체의 상속으로 사용될 수 있다.

생성자에서만 상속이 의미를 가진다.

<body>
    <script>
        const grandParent = function() 
        {
            this.stock = 'MS 100주'
            
        }
        grandParent.prototype.money = '100억';
        grandParent.prototype.realEstate = '여의도 자이 아파트';

        const parent = function() 
        {
            this.stock = 'TESLA 500주'
            this.apple = 'I MAC'
        }
        parent.prototype = new grandParent();

        

        const myson = function() 
        {

        }
        myson.prototype = new parent();

        const my = new myson();

        console.log(my.money)
        console.log(my.stock)
        console.log(my.realEstate)
        console.log(my.apple)

        //100억
        //TESLA 500주
        //여의도 자이 아파트
        //I MAC

    </script>
</body>

 

 

Prototype Chin

역으로 거슬러 올라가서 값을 찾는다.

value가 child에 없기때문에 상위 프로토타입을 역추적하여 연결되면서 찾아간다.

* 복잡성 때문에 사용하지 않는다. ES5의 방식이며 현대서는 Class를 사용한다.

 

 

Prototype을 이용한 기능 확장

  • 내장 객체의 Prototype에 원하는 기능을 추가하여 활용할 수 있다.
  • 내장 객체(Built-in Object)란 자바스크립트가 기본적으로 가지고 있는 Array, Ojbect, Function, Math 등을 말한다.
  • 내장 객체의 Prototype에 원하는 기능을 추가하여 활용할 수 있다.
  • this를 주의 깊게 봐야 한다.

 

 

예제

점심 메뉴의 배열을 만들고 배열의 요소를 랜덤 하게 리턴하는 함수를 만드시오.

<body>
    <script>
        const getRandomElement = function(menu)
        {   
            return menu[Math.floor(Math.random() * menu.length)]
        }

        const menu = new Array('마라탕', '국밥', '분식', '백반', '중식', '샐러드')

        console.log(getRandomElement(menu))
        
    </script>
</body>

 

참고 : 난수 발생

https://cruella-de-vil.tistory.com/44

 

[JavaScript] 특정 범위 랜덤수 생성하여 버블소팅하기. Math

랜덤수를 추출하기 위해서는 내장객체 Math중 Math.random과 Math.foor()를 사용해야한다. Math 내장 객체중 가장 많이 사용되는 4가지에 대해 먼저 알아보겠다. Math.random() Math.floor() Math.round() Math.c..

cruella-de-vil.tistory.com

 

예제+

배열의 요소를 랜덤 하게 리턴하는 함수를 Array의 prototype의 method로 만드시오.

<body>
    <script>
        Array.prototype.getRandomElement = function()
        {
            return this [Math.floor(Math.random() * this.length)];
        }

        const menu = new Array('마라탕', '국밥', '분식', '백반', '중식', '샐러드')

        const brand = ['benz', 'hyundai', 'honda', 'kia', 'ford'];

        console.log(menu.getRandomElement())
        console.log(brand.getRandomElement())
    </script>
</body>

 

반응형

'JavaScript' 카테고리의 다른 글

[JavaScript] Constructor 예제  (2) 2022.04.19
[JavaScript] new.target  (0) 2022.04.19
[JavaScript] Closure(클로저) 예제  (0) 2022.04.18
[JavaScript] 객체지향, Constructor(생성자), new  (0) 2022.04.18
[JavaScript] apply()  (0) 2022.04.18