Javascript Prototype

서동수·2022년 7월 20일

자바스크립트는 프로토타입 기반 프로그래밍 언어이다.

자바스크립트에서는 클래스 없이 객체를 생성할 수 있으며
모든 객체가 자신의 부모 역할을 담당하는 객체와 연결되어 있다.
이것은 상속 개념과 비슷하게 부모 객체의 프로퍼티, 메소드를 상속받아 사용할 수 있게 한다.
이러한 부모 객체를 Prototype 객체라고 한다.

function Person(name) {
  this.name = name;
}

var foo = new Person('Lee');

console.dir(Person); // prototype 프로퍼티가 있다.
console.dir(foo);    // prototype 프로퍼티가 없다.

[[Prototype]]

  • 함수를 포함한 모든 객체가 가지고 있으며 객체에서는 자신의 부모역할을 하는 프로토 타입 객체를 가리킨다. 함수 객체의 경우 Function.prototype을 가리킨다.

prototype 프로퍼티

  • 함수 객체만 가지고 있느 프로퍼티로 함수 객체가 생성자로 사용될 때 이 함수를 통해
    객체의 부모 역학을 하는 객체를 가리킨다.
    위에서 foo [[prototype]] 은 Person이 되는 것이다.
console.log(Person.prototype === foo.__proto__);

Constructor

  • 프로토타입 객체는 constructor 프로퍼니를 갖는데 이 constructor는 객체 입장에서 자신을 생성한 객체를 가리키게 된다.

위에서 Person() 생성자 함수에 의해 생성된 객체가 foo 였는데
foo객체를 생성한 객체는 Person()생성자 함수이다.
foo 프로토타입 객체는 Person.prototype 이고
Person.prototype의 constructor 프로퍼티는 Person()생성자 함수를 가리킨다.

function Person(name) {
  this.name = name;
}

var foo = new Person('Lee');

// Person() 생성자 함수에 의해 생성된 객체를 생성한 객체는 Person() 생성자 함수이다.
console.log(Person.prototype.constructor === Person);

// foo 객체를 생성한 객체는 Person() 생성자 함수이다.
console.log(foo.constructor === Person);

// Person() 생성자 함수를 생성한 객체는 Function() 생성자 함수이다.
console.log(Person.constructor === Function);
profile
devLog

0개의 댓글