Prototype

Prototype : 객체의 원형

함수는 객체, 그러므로 생성자로 사용될 함수도 객체임

객체는 프로퍼티(property)를 가질 수 있는데 prototype이라는 프로퍼티는 그 용도가 약속되어 있는 특수한 프로퍼티

1. Prototype Chain

prototype은 객체와 객체를 연결하는 체인의 역할 객체에 저장된 속성들을 생성자를 통해서 객체가 만들어질 때 그 객체에 연결

function Ultra(){}
Ultra.prototype.ultraProp = true;
 
function Super(){}
Super.prototype = new Ultra(); 
//*주의! Super.prototype = Ultra.prototype 으로하면 안됨
//부모관계인 Ultra.prototype의 값 또한 변경되기 때문
 
function Sub(){}
Sub.prototype = new Super(); //Super.prototype을 원형으로 하는 객체 생성
 
var o = new Sub(); //Sub.prototype을 원형으로 하는 객체 생성
console.log(o.ultraProp);
//true

생성자 Sub를 통해서 만들어진 객체 o가 Ultra의 프로퍼티 ultraProp에 접근 가능한 것은 prototype 체인으로 Sub와 Ultra가 연결되어 있기 때문

  1. 객체 o에서 ultraProp를 찾는다.

  2. 없다면 Sub.prototype.ultraProp를 찾는다.

  3. 없다면 Super.prototype.ultraProp를 찾는다.

  4. 없다면 Ultra.prototype.ultraProp를 찾는다.

Last updated