자바스크립트 (프로토타입)

이종경·2024년 4월 13일
0

자바스크립트

목록 보기
4/11
post-thumbnail

예전에 코딩애플의 강의를 들었을 때, prototype 객체의 개념을 부모 객체의 유전자라고 생각하라 하였고 부모의 유전자를 검사할 땐 __proto__를 사용하라고 했다. 이를 생각하며 이해하려 노력하면 조금은 쉽게 다가갈 수 있는 것 같다.

1. 부모 객체, Prototype(프로토타입) 객체

자바스크립트는 프로토타입 기반 객체지향 프로그래밍 언어로, 클래스 없이 객체를 생성할 수 있는 언어이다. 물론 ES6부터 클래스가 추가되었다.

자바스크립트의 모든 객체는 자신의 부모 역할을 담당하는 객체와 연결되어 있다. 그리고 이것은 마치 객체 지향의 상속 개념과 같이 부모 객체의 프로퍼티 또는 메소드를 상속받아 사용할 수 있게 한다. 이러한 부모 객체를 Prototype(프로토타입) 객체 이라 한다.

function Person(name) { // Person의 프로토타입 객체(유전자)는 Function.prototype
  this.name = name;
}

var foo = new Person('Lee'); // foo의 프로토타입 객체(유전자)는 Person.prototype

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

console.dir(Person.prototype) // Object
console.dir(foo.prototype) // undefined

함수형 객체는 prototype 프로퍼티를 소유하게 되고 [[Prototype]] 인터널 슬롯도 갖는다.

2. [[Prototype]]과 prototype 프로퍼티는 뭐가 다른가?

[[prototype]] 인터널 슬롯과 prototype 프로퍼티는 모두 프로토타입 객체를 가리키지만 관점에서 차이가 있다.

  • [[prototype]]
    • 함수를 포함한 모든 객체가 가지고 있는 인터널 슬롯이다.
    • 객체의 입장에서 자신의 부모 역할을 하는 프로토타입 객체를 가리키며 함수 객체의 경우 Function.prototype를 가리킨다.
console.log(Person.__proto__ === Function.prototype); // true
  • prototype 프로퍼티
    • 함수 객체만 가지고 있는 프로퍼티이다.
    • 함수 객체가 생성자로 사용될 때 이 함수를 통해 생성될 객체의 부모 역할을 하는 객체(프로토타입 객체)를 가리킨다.
console.log(Person.prototype === foo.__proto__); // true

3. constructor 프로퍼티

constructor 프로퍼티는 객체의 입장에서 자신을 생성한 객체를 가리킨다.
함수도 일급 객체로서 객체라는 사실에 유념하며 아래의 예시를 살펴보자.

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);

4. 원시타입의 확장

var str = 'test';
console.log(typeof str);                 // string
console.log(str.constructor === String); // true
console.dir(str);                        // test

var strObj = new String('test');
console.log(typeof strObj);                 // object
console.log(strObj.constructor === String); // true
console.dir(strObj);
// {0: "t", 1: "e", 2: "s", 3: "t", length: 4, __proto__: String, [[PrimitiveValue]]: "test" }

console.log(str.toUpperCase());    // TEST
console.log(strObj.toUpperCase()); // TEST

원시 타입으로 프로퍼티나 메소드를 호출할 때 원시 타입과 연관된 객체로 일시적으로 변환되어 프로토타입 객체를 공유하게 된다.

프로토타입편을 마무리하며

prototype(프로토타입)은 부모의 유전자, 부모의 유전자를 검사하고자 할 땐 __proto__, 유전자를 만든 객체나 객체를 만든 객체를 검사할 땐 constructor

참고
자바스크립트의 기본

profile
작은 성취들이 모여 큰 결과를 만든다고 믿으며, 꾸준함을 바탕으로 개발 역량을 키워가고 있습니다

0개의 댓글