Language/Javascript

프로토타입 prototype (2) : prototype 프로퍼티

bright jazz music 2025. 5. 7. 21:56

함수 객체의 prototype 프로토타입

 

prototype 프로퍼티는 함수객체만이 소유하며  생성자 함수가 생성할 인스턴스의 프로토타입을 가리킨다.

// 함수 객체는 prototype 프로퍼티를 소유한다.
(function () {}).hasOwnProperty('prototype'); // true

// 일반 객체는 prototype 프로퍼티를 소유하지 않는다.
({}).hasOwnProperty('prototype'); // false

 

prototype 프로퍼티는 생성자 함수로 호출할 수 없는 함수들

 

// 화살표 함수는 non-constructor
const Person = name = > {
	this.name = name;
}

// non-constructor는 prototype 프로퍼티를 소유하지 않는다.
console.log(Person.hasOwnProperty('prototype')); // false

// non-constructor는 프로토타입을 생성하지 않는다.
console.log(Person.prototype); // undefined

// ES6의 메서드 축약 표현으로 정의한 메서드는 non-constructor이다.
const obj = {
	foo() {}
}
console.log(obj.foo.hasOwnProperty('prototype')); // false

// non-constructor는 프로토타입을 생성하지 않는다.
console.log(obj.foo.prototype);// undefined

 

Object.prototype으로부터 상속 받아 모든 객체가 가지고 있는 __proto__ 접근자 프로퍼티와 함수 객체만이 가지고 있는 prototype 프로퍼티는 결굴 동일한 프로토 타입을 가리킨다. 하지만 이들 프로퍼티를 사용하는 주체가 다르다.

 

  • __proto__  접근자 프로퍼티는 모든 객체가 소유하며, 모든 객체가 자신의 프로토타입에 접근하거나 프로토타입을 교체하기 위해 사용할 수 있다. 
  • prototype 프로퍼티는 생성자 함수(constructor)가 소유하며 생성자 함수가 자신이 생성할 객체(인스턴스)의 프로토타입을 할당하기 위해 사용한다.
// 생성자 함수
function Person(name) {
	this.name = name;
}

const me = new Person('Lee');

// 결국 Person.prototype과 me.__proto__는 동일한 프로토타입을 가리킨다.
console.log(Person.prototype = me.__proto__); // true

 

 

 

모든 프로토타입은 constructor 프로퍼티를 갖는다. 이 constructor 프로퍼티는 prototype 프로퍼티로 자신을 참조하고 있는 생성자 함수를 가리킨다. 이러한 연결은 생성자 함수가 생성될 때, 즉 함수 객체가  생성될 때 이루어진다.

// 생성자 함수
function Person(name) {
	this.name = name;
}

const me = new Person('Lee');

// me 객체의 생성자 함수는 Person이다
console.log(me.constructor === Person); // true