예전에 코딩애플의 강의를 들었을 때, prototype 객체의 개념을 부모 객체의 유전자
라고 생각하라 하였고 부모의 유전자를 검사할 땐 __proto__
를 사용하라고 했다. 이를 생각하며 이해하려 노력하면 조금은 쉽게 다가갈 수 있는 것 같다.
자바스크립트는 프로토타입 기반 객체지향 프로그래밍 언어
로, 클래스 없이 객체를 생성할 수 있는 언어이다. 물론 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]] 인터널 슬롯
도 갖는다.
[[prototype]] 인터널 슬롯과 prototype 프로퍼티는 모두 프로토타입 객체를 가리키지만 관점에서 차이가 있다.
모든 객체가 가지고 있는 인터널 슬롯
이다.객체
의 입장에서 자신의 부모 역할을 하는 프로토타입 객체를 가리키며 함수
객체의 경우 Function.prototype를 가리킨다.console.log(Person.__proto__ === Function.prototype); // true
함수 객체만 가지고 있는 프로퍼티
이다.생성자로 사용될 때
이 함수를 통해 생성될 객체의 부모 역할을 하는 객체(프로토타입 객체)
를 가리킨다.console.log(Person.prototype === foo.__proto__); // true
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);
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
참고
자바스크립트의 기본