본문 바로가기
JavaScript

프로토타입(prototype) - constructor 프로퍼티

by whoyoung90 2022. 5. 29.
반응형

생성자 함수의 프로퍼티인 prototype 객체 내부에는 constructor 라는 프로퍼티가 있다.

인스턴스의 __proto__ 객체 내부에도 마찬가지로 존재한다.

 

이 프로퍼티는 단어 그대로 자기 자신을 참조한다.

즉, 인스턴스의 생성자 정보를 알아내는 수단으로 보면 된다.

 

constructor: f (name)
constructor: f Array()

let arr = [1, 2];
Array.prototype.constructor === Array;  // true 자기 자신
arr.__proto__.constructor === Array;    // true 자기 자신
arr.constructor === Array;              // true

let arr2 = new Array(3, 4);
let arr3 = new arr.constructor(3, 4);  // arr.constructor === Array

console.log(arr2);  // [ 3, 4 ]
console.log(arr3);  // [ 3, 4 ]

그러므로 다음 각 줄은 모두 동일한 대상을 가리킨다고 정리할 수 있다.

[Constructor]
[Constructor].prototype.constructor
[instance].__proto__.constructor
[instance].constructor
Object.getPrototypeOf([instance]).constructor

다음 각 줄도 모두 동일한 객체(prototype)에 접근할 수 있다.

[Constructor].prototype
[instance].__proto__
[instance] // 우리가 사용하고 있던 것
Object.getPrototypeOf([instance])

 

 

반응형

'JavaScript' 카테고리의 다른 글

객체 전용 메서드란?  (0) 2022.06.06
프로토타입 체이닝 (prototype chaining)  (0) 2022.06.04
프로토타입(prototype) 디렉터리 구조  (0) 2022.05.28
프로토타입(prototype)  (0) 2022.05.22
커링 함수  (0) 2022.05.21

댓글