JavaScript Prototype Chain

CodeLog·2020년 12월 9일
0

Prototype Chain이란?

특정 객체의 메서드나 프로퍼티에 접근하고자할 때, 해당 객체에 접근하려고 하는 프로퍼티나 객체가 없다면 프로토타입 링크([[Prototype]] 프로퍼티)를 따라 자신의 부모 역할을 하는 프로토타입 객체를 차례로 검색한다. 이를 프로토타입 체인이라 한다.
참고:https://bkdevlog.netlify.app/posts/prototypechain-of-js

prototype

함수 객체만 가지고 있는 프로퍼티이다.
함수 객체가 생성자로 사용될 때, 이 함수를 통해 생성될 객체의 부모 역할을 하는 객체(Prototype 객체)를 가리킨다.
즉, Prototype 객체란 어떠한 객체가 만들어지기 위해 그 객체의 모태가 되는 객체이고 하위 객체들에게 물려줄 속성들이다.

__porto__

함수를 포함한 모든 객체가 가지고 있는 인터널 슬롯이다.
객체의 입장에서 자신의 부모 역할을 하는 Prototype 객체를 가리킨다.
ECMAScript에서는 암묵적 프로토타입 링크(implicit prototype link)라 부르며 proto 프로퍼티에 저장된다.
Prototype 프로퍼티는 함수의 입장에서 자신과 링크된 자식에게 물려줄 프로토타입 객체를 가리키고, proto 프로퍼티는 객체의 입장에서 자신의 부모 객체인 프로토타입 객체를 내부의 숨겨진 링크로 가지고 있는 것이다.

constructor

프로토타입 객체는 constructor 프로퍼티를 가진다.
constructor 프로퍼티는 생성된 객체(인스턴스)의 입장에서 자신을 생성한 함수를 가리킨다.

prototype Chain의 참조관계를 보여주는 예시코드입니다.

var Human = function(name){
  this.name = name;
}
Human.prototype.sleep = function(){
  console.log('zzz');
}
var student = new Human('lee');

//student의 참조는 Human
console.log(student.__proto__ === Human.prototype);
//student의 참조의 참조는 Object
console.log(student.__proto__.__proto__ === Object.prototype);
//student의 생성자는 Human
console.log(student.constructor === Human);

이러한 객체들간의 참조를 활용하여 상속의 효과를 낼수있습니다.

var Human = function(name){
  this.name = name;
}
Human.prototype.sleep = function(){
  console.log('zzz');
}
var steve = new Human('steve')
Human.prototype.sleep = function(){console.log('zzz')};

function Student (){
}
Student.prototype.learn = function (){
  console.log('배우는중')
}
//Human의 객체를 Student에 복제하여 상속관계를 만든다.
Student.prototype = Object.create(Human.prototype);
//상속관계를만들고 constructor를 Student로 할댕 해 주지 않으면
//constructor는 Human을 바라보게 된다
//이유는 위에서 객체를 복제했기때문이다.
Student.prototype.constructor = Student;
//Student의 instance를 만든다.
let student = new Student();
console.log(student instanceof Human)//	true
console.log(student instanceof Student)//	true
console.log(student.__proto__)//Student
student.sleep();//zzz

참고:https://iamsjy17.github.io/javascript/2019/06/10/js33_17_prototype.html

profile
개발로그

0개의 댓글