Prototype (프로토타입)

parkjh9370·2021년 12월 23일
0

👍 항상 검색하며 의문을 가졌던 mdn문서 method에 왜 prototype이 붙는지 드디어 이해 할 수 있었다!!

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤⏤

[prototype]

  • Constructor 생성 시 가지게 되는 속성을 말함
  • Constructor 를 부모, 이를 통해 변수를 만들어 줄 시 자식 이라고 함
    예시)
	function MakeStudent(name, age) {
            // this: constructor 새로 생성되는 object (instance)
            // 새로 생성되는 name(key)에 "Kim"(value) 넣기
            this.name = name;
            this.age = age;
            this.sayHi = () => {
                console.log('안녕하세요 ' + this.name+ ' 입니다')
            }
        }
        let student = new MakeStudent('Park', 20);

해당 코드에서 Makestudent : 부모 / student : 자식


  • 자바스크립트의 경우 변수 생성 시 constructor 구조로 변수를 만들게 되어 있음
    예시)

array 생성 코드

	let array = [1, 2, 3]

실제 컴퓨터에서 array 생성 방식 (constructor 생성)

	let array = new Array(1,2,3);

생성되는 constructor 의 경우 prototype(유전자) 속성이 생김
이 때 protype 객체에 값을 할당해주면 모든 자식들이 값을 공유하여 사용할 수 있다.

위의 코드를 응용해 console.log 값을 출력해 보면

	function MakeStudent(name, age) {
            // this: constructor 새로 생성되는 object (instance)
            // 새로 생성되는 name(key)에 "Kim"(value) 넣기
            this.name = name;
            this.age = age;
            this.sayHi = () => {
                console.log('안녕하세요 ' + this.name+ ' 입니다')
            }
        }

        let student = new MakeStudent('Park', 20);

		console.log(MakeStudent.prototype) 	// {constructor: ƒ}

		MakeStudent.prototype.gender = 'Men'   // 새로운 속성 할당

		console.log(student.gender) // Men

		console.log(student)  // MakeStudent {name: 'Park', age: 20, sayHi: ƒ}
		

-> 첫번째 출력값에서 보는바와 같이 prototype(객체) 속성이 생성 되는 것을 볼 수 있음.

-> 하지만 마지막 console.log(student)의 경우 prototype에 gender(Key), 'Men'(Value) 값을 할당했음에도 이를 가지고 있지 않음을 볼 수 있는데

-> 이는 자바스크립트의 특징 인데 해당 값이 없으면 부모를 탐색, 없으면 부모의 부모를 탐색, 없으면 부모의 부모의 부모를 탐색, ... 하는 방식으로 이루어지기 때문이다.

  • 즉 prototype에 gender, 'men' 이라는 key, value 값을 넣어줬음으로 해당 student에는 이를 포함하고 있지 않음
  • 하지만 student.gender에서 gender라는 키의 밸류값을 찾기 위해 부모 객체인 prototype으로 탐색을 가게 되고 이를 찾게 되면 출력해 주게 되는 방식

<자바스크립트 내장 함수 작동 원리>

이를 통해 자바스크립트에서 객체, 배열에서 흔히 쓰이는 toString(), map(), filter() 등의 내장함수 작동 원리를 파악 할 수 있음.

예시 코드

let array = [1,2,3]  
    /** 우리가 배열을 만들었을 때 실제 컴퓨터 생성 방식: let array = new Array(1,2,3)
    * 컴퓨터에서는 constructor(부모)를 만들게 되고 prototype 속성을 가지고 있음
    * 이 prototype의 경우 우리가 흔히 쓰는 map(), filter()등의 내장함수를 가지고 있음
    */

// 부모 프로토타입을 출력해보면 
console.log(array.__proto__) // 콘솔창을 통해 출력해 보면 join, filter, sort 등 배열에서 쓸 수 있는 내장함수를 담고 있는 것을 볼 수 있음
//[constructor: ƒ, concat: ƒ, copyWithin: ƒ, fill: ƒ, find: ƒ, …]

array.filter((li) => li < 3) // [1,2]
    

따라서 위와 같은 내장함수 filter를 사용했을 때 실제 array에는 filter라는 내장함수가 없지만
부모(Constructor)의 prototype에는 filter 내장함수가 있음으로 이를 찾아가서 쓸 수 있게 되는 것.



0개의 댓글