Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

옥수수, 기록

JavaScript 프로토타입 체인, __proto__, .prototype 본문

카테고리 없음

JavaScript 프로토타입 체인, __proto__, .prototype

ok-soosoo 2022. 11. 21. 11:55

** 이하 속성(property), 객체(object)

프로토타입 체인?

  • 자바스크립트는 객체에 속성을 조회할 때 해당 속성이 없으면 숨겨져 있는 [[Prototype]]속성을 조회하게 되는데 이것을 프로토타입 상속이라고 한다.
  • __proto__ 속성을 사용하면 자신의 [[prototype]] 객체에 접근할 수 있다.
let computer = {
	mouse: 'logitec',
	speaker: 'harman',
	monitor: 'LG',
	internet: 'SKB'
	[[Prototype]](안보임)
}

let macbook = {
	mouse: 'apple',
	speaker: 'apple',
	monitoer: 'LG'
}

macbook.internet; // JS : 없는 속성이네 Prototype을 참조해보자
				 // 참조해도 없네 undefined
  • 여기서 __proto__ 속성에 다른 변수를 지정해주면 그 변수의 속성값을 참조하라고 할 수 있다.
let computer = {
	mouse: 'logitec',
	speaker: 'harman',
	monitor: 'LG',
	internet: 'SKB'
}

let macbook = {
	mouse: 'apple',
	speaker: 'apple',
	monitoer: 'LG',
    __proto__: computer
}

macbook.internet; // macbook에는 속성이 없는데..
					어? computer를 참조하라고 돼있네
					'SKB'
  • 이렇게 프로토타입 상속이 일어날 때, 접근자 __proto__를 따라 참조하는 부모 프로토타입의 속성을 순차적으로 검색하는 것, 이것을 프로토타입 체인이라고 한다.

.prototype

  • 함수는 숨겨져있는 [[Prototype]]속성이 있다.
1. 함수도 기본적으로 [[Prototype]]속성을 가지고 있다.

function func() {}
// func.prototype = {constructor: func}
  • 생성자 함수의 사용
2. 생성자 함수를 사용해 새 변수에 할당해 주면 
그 변수는 함수가 갖고있던 기본 [[Prototype]]속성을 그대로 가지고 간다

function func() {}

let variation = new func();
// variation.prototype.constructor === func
  • .prototype의 사용
3. 생성자함수명.prototype = 다른 변수
		로 지정해주면 생성자함수를 사용해 만든 새로운 객체의 [[Prototype]]속성은 
		다른 변수의 [[Prototype]]을 따라간다

function func() {}

let a = {
	property: '1'
}


func.prototype = a;
// new func를 호출해 만든 새로운 객체의 [[Prototype]]속성을 a로 설정해!


let variation = new func();
variation.property // '1'
Comments