일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- 해쉬
- 빅오
- styled-components
- react
- aws lightsail
- 슬라이딩윈도우
- isNaN
- 투포인터
- 알고리즘
- 라이프사이클
- next.js
- typscript
- TypeScript
- NextAuth
- never타입
- 버블정렬
- nextjs
- 큐
- JavaScript
- cookie
- textarea autosize
- tailwindcss
- js알고리즘
- 스택
- 블로그만들기
- 정렬
- 그리디
- Algorithm
- react-query
- nestjs
- Today
- Total
far
[Javascript] 프로토타입(Prototype) 본문
1. 프로토타입이란?
자바스크립트는 프로토타입 기반의 객체지향 프로그래밍 언어이다. 그래서 프토로타입은 ES6에서 클래스 문법이 도입되기 이전에 객체 지향 프로그래밍(OOP)의 핵심을 맡고 있었다. 게다가 클래스 문법 또한 완전히 새로운 객체지향 모델을 제공하는 것이 아니라 프로토타입 기반 패턴의 문법 변형이라고 볼 수 있다.
(사실 클래스는 생성자 함수(new)는 동일하게 작동하지 않으며, 클래스가 좀 더 엄격하고 생성자 함수에서 제공하지 않는 기능도 제공하기 때문에 새로운 객체 생성 매커니즘으로 보는 것이 좀 더 합당할 수도 있다.)
1.1 상속과 프로토타입
자바스크립트는 프로토타입을 기반으로 상속을 구현한다.
// 생성자 함수
function Circle(radius) {
this.radius = radius;
}
// Circle 생성자 함수가 생성한 모든 인스턴스가 getArea 메서드를
// 공유해서 사용할 수 있도록 프로토타입에 추가한다.
// 프로토타입은 Circle 생성자 함수의 prototype 프로퍼티에 바인딩되어 있다.
Circle.prototype.getArea = function () {
return Math.PI * this.radius ** 2;
};
// 인스턴스 생성
const circle1 = new Circle(1);
const circle2 = new Circle(2);
// Circle 생성자 함수가 생성한 모든 인스턴스는 부모 객체의 역할을 하는
// 프로토타입 Circle.prototype으로부터 getArea 메서드를 상속받는다.
console.log(circle1.getArea === circle2.getArea); //true
console.log(circle1.getArea()); // 3.1415...
console.log(circle2.getArea()); // 12.5663...
공통적으로 사용할 프로퍼티나 메서드를 프로토타입에 미리 구현해두면 생성자 함수가 생성할 모든 인스턴스는 별도의 구현 없이 상위(부모) 객체인 프로토타입의 자산을 공유하여 사용할 수 있다.
2. 프로토타입 객체
일반적으로 우리가 프로토타입이라고 부르는게 프로토타입 객체이다. 객체가 생성될 때 생성 방식에 따라 프로토타입이 결정되고 [[Prototype]]에 저장된다.
2.1. __proto__ 접근자 프로퍼티
모든 객체는 __proto__를 통해 [[Prototype]] 내부 슬롯에 간접적으로 접근할 수 있다.
내부 슬롯은 프로퍼티가 아니기 때문에 직접적으로 접근하거나 호출할 수 없지만, __proto__ 접근자 프로퍼티를 통해 프로토타입에 접근할 수 있게 된다.
const obj = {};
const parent = { x:1 };
// getter
obj.__proto__;
// setter
obj.__proto__ = parent;
console.log(obj.x); // 1
모든 객체는 상속을 통해 Object.prototype.__proto__ 접근자 프로퍼티를 사용할 수 있다.
const person = { name: 'Lee' };
// person 객체는 __proto__ 프로퍼티를 소유하지 않는다.
console.log(person.hasOwnProperty('__proto__')); // false
// __proto__ 프로퍼티는 모든 객체의 프로토타입 객체인 Object.prototype의 접근자 프로퍼티다.
console.log(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'));
// {get: f, set: f, enumerable: false, configurable: true}
// 모든 객체는 Object.prototype의 접근자 프로퍼티 __proto__를 상속받아 사용할 수 있다.
console.log({}.__proto__ === Object.prototype); // true
__proto__를 통해 프로토타입에 접근하면 상호 참조에 의해 프로토타입 체인이 생성되는 것을 방지할 수 있다.
const parent = {};
const child = {};
child.__proto__ = parent;
parent.__proto__ = child; // TypeError: Cyclic __proto__ value
__proto__를 사용할 수 없는 경우
// obj는 프로토타입 체인의 종점이기 때문에 Object.__proto__를 상속받을 수 없다.
consst obj = Object.create(null);
console.log(obj.__proto__); // undefined
// __proto__대신 프로토타입의 참조를 취득하고 싶으면 Object.getPrototypeOf를 사용
console.log(Object.getPrototypeOf(obj)); // null
2.2. 함수 객체의 prototype 프로퍼티
prototype 프로퍼티는 함수 객체만이 소유할 수 있으며 생성자 함수가 생성할 인스턴스의 프로토타입을 가리킨다.
// 함수 객체는 prototype 프로퍼티를 소유한다.
(function () {}).hasOwnProperty('prototype'); // true
// 일반 객체는 prototype 프로퍼티를 소유하지 않는다.
({}).hasOwnProperty('prototype'); // false
생성자 함수로 호출할 수 없는 함수(non-constructor)인 화살표 함수나 ES6+ 메서드 축약 표현으로 정의한 메서드는 prototype 프로퍼티를 소유하지 않기 때문에 프로토타입도 생성하지 않는다. 또한, 프로퍼티를 소유하지만 객체를 생성하지 않는 일반 함수의 prototype 프로퍼티는 아무런 의미가 없다.
모든 객체가 가지고 있는 __proto__접근자 프로퍼티와 함수 객체만이 가지고 있는 prototype 프로퍼티는 동일한 프로토타입을 가리킨다. 하지만 프로퍼티를 사용하는 주체는 다르다.
구분 | 소유 | 값 | 사용 주체 | 사용 목적 |
__proto__ 접근자 프로퍼티 |
모든 객체 | 프로토타입의 참조 | 모든 객체 | 객체가 자신의 프로토타입에 접근 또는 교체하기 위해 사용 |
prototype 프로퍼티 |
constructor | 프로토타입의 참조 | 생성자 함수 | 생성자 함수가 자신이 생성할 객체(인스터스)의 프로토타입을 할당하기 위해 사용 |
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
console.log(Person.prototype === me.__proto__); // true
2.3. 프로토타입의 constructor 프로퍼티와 생성자 함수
모든 프로토타입은 constructor 프로퍼티를 갖는다. 이 constructor 프로퍼티로 자신을 참조하고 있는 생성자 함수를 가리킨다.
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
// me 객체의 생성자 함수는 Person이다.
console.log(me.constructor === Person); // true
3. 프로토타입의 생성 시점
프로토타입은 생성자 함수가 생성되는 시점에 더불어 생성된다. 프로토타입과 생성자 함수는 단독으로 존재할 수 없고 언제나 쌍으로 존재하기 때문이다.
3.1. 사용자 정의 생성자 함수와 프로토타입 생성 시점
생성자 함수로서 호출할 수 있는 함수, 즉 constructor는 함수 정의가 평가되어 함수 객체를 생성하는 시점에 프로토타입도 생성된다.
// 함수 정의(constructor)가 평가되어 함수 객체를 생성하는 시점에 프로토타입도 더불어 생성된다.
console.log(Person.prototype); // {constructor: f}
function Person(name) {
this.name = name;
}
호이스팅에 의해 함수 선언문이 런타임 이전에 실행되기 때문에 Person 생성자 함수는 어떤 코드보다 먼저 평가되어 함수 객체가 된다. 이 때 프로토타입도 더불어 생성되며, 생성된 프로토타입은 Person 생성자 함수의 prototype 프로퍼티에 바인딩된다.
3.2. 빌트인 생성자 함수와 프로토타입 생성 시점
Object, String, Function, Promise 등과 같은 빌트인 생성자 함수도 일반 함수와 마찬가지로 빌트인 생성자 함수가 생성되는 시점에 프로토타입이 생성되며, 전역 객체가 생성되는 시점에 생성된다. 생성된 프로토타입은 빌트인 생성자 함수의 prototype 프로퍼티에 바인딩된다.
4. 객체 생성 방식과 프로토타입의 결정
객체는 다음과 같이 다양한 생성 방법이 있다.
- 객체 리터럴
- Object 생성자 함수
- 생성자 함수
- Object.create 메서드
- 클래스(ES6)
이들은 객체 생성 방식의 차이는 있으나 추상 연산(OrdinaryObjectCreate)에 의해 생성된다.
4.1. 객체 리터럴에 의해 생성된 객체의 프로토타입
객체 리터럴에 의해 생성된 객체는 Object.prototype을 프로토타입으로 갖게 되며, Object.prototype을 상속받는다. 이 객체는 constructor 프로퍼티와 hasOwnProperty 메서드 등을 소유하진 않지만, Object.prototype을 상속 받았기 때문에 이 메서드들을 자신의 자산인 것처럼 사용할 수 있다.
4.2. Object 생성자 함수에 의해 생성된 객체의 프로토타입
객체 리터럴과 Object 생성자 함수에 의한 객체 생성 방식의 차이는 프로퍼티를 추가하는 방식에 있다.
const obj = new Object();
obj.x = 1;
Object 생성자 함수 방식은 빈 객체 생성 후 프로퍼티를 추가해야한다.
4.3. 생성자 함수에 의해 생성된 객체의 프로토타입
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`My name is ${this.name}`);
};
const me = new Person('Lee');
me.sayHello(); // My name is Lee
위의 예시처럼 Person 생성자 함수를 통해 생성된 모든 객체는 프로토타입에 추가된 sayHello 메서드를 상속받아 자신의 메서드처럼 사용할 수 있다. 이렇게 추가/삭제된 프로퍼티는 프로토타입 체인에 즉각 반영된다.
5. 프로토타입 체인
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`My name is ${this.name}`);
};
const me = new Person('Lee');
console.log(me.hasOwnProperty('name')); // true
4.3의 예제에서 hasOwnProperty를 호출할 수 있다. 이것은 생성자 함수에 의해 생성된 객체의 프로토타입은 Person.prototype 뿐만 아니라 Object.prototype도 상속받았다는 것을 의미한다.
자바스크립트는 객체의 프로퍼티(메서드 포함)에 접근하려고 할 때 접근하려는 프로퍼티가 없으면 [[Prototype]] 내부 슬롯의 참조를 따라 자신의 부모 역할을 하는 프로토타입 프로퍼티를 순차적으로 검색한다. 이를 프로토타입 체인이라고 한다. 프로토타입 체인은 자바스크립트가 객체지향 프로그래밍의 상속을 구현하는 메커니즘이다. 프로토타입 체인의 최상위에 위치하는 객체인 Object.prototype을 프로토타입 체인의 종점이라고 한다. 만약 Object.prototype에서도 프로퍼티를 검색할 수 없다면 에러가 아닌 undefined를 반환한다.
프로토타입 체인은 스코프 체인(식별자 검색을 위한 메커니즘)과 별도로 동작하는게 아니라 서로 협력하여 식발자와 프로퍼티를 검색하는데 사용된다.
6. 프로토타입의 교체
프로토타입은 임의의 다른 객체로 변경할 수 있다.
6.1. 생성자 함수에 의한 프로토타입의 교체
const Person = (function () {
function Person(name) {
this.name = name;
}
Person.prototype = {
// constructor 프로퍼티와 생성자 함수 간의 연결을 설정
constructor: Person,
sayHello() {
console.log(`My name is ${this.name}`);
}
};
return Person;
}());
const me = new Person('Lee');
console.log(me.constructor === Person); // true
프로토타입을 교체하면 constructor 프로퍼티와 생성자 함수 간의 연결이 파괴되기 때문에 constructor 프로퍼티를 추가해야한다.
6.2. 인스턴스에 의한 프로토타입의 교체
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
const parent = {
// constructor 프로퍼티와 생성자 함수 간의 연결을 설정
constructor: Person,
sayHello() {
console.log(`My name is ${this.name}`);
}
};
Person.prototype = parent;
// me 객체의 프로토타입을 parent 객체로 교체
Object.setPrototypeOf(me, parent);
// me.__proto__ = parent; 와 동일하게 동작한다.
me.sayHello(); // My name is Lee
console.log(me.constructor === Person); // true
// 생성자 함수의 prototype프로퍼티가 교체된 프로토타입을 가리킨다.
console.log(Person.prototype === Object.getPrototypeOf(me)); // true
7. 직접 상속
6의 교체는 상당히 번거롭다. 그래서 보통 직접 상속을 사용한다.
7.1 Object.create에 의한 직접 상속
Object.create 메서드의 첫 번째 매개변수에는 생성할 객체의 프로토타입으로 지정할 객체를 전달한다. 두번째 매개변수에는 생성할 객체의 프로퍼티 키와 프로퍼티 디스크립터 객체로 이루어진 객체를 전달한다. 이 객체의 형식은 Object.defineProperties 메서드의 두 번째 인수와 동일하다. 두 번째 인수는 옵션이므로 생략 가능하다.
// 프로토타입이 null인 객체를 생성한다. 생성된 객체는 프로토타입 체인의 종점에 위치한다.
// obj → null
let obj = Object.create(null);
console.log(Object.getPrototypeOf(obj) === null); // true
// Object.prototype을 상속받지 못한다.
console.log(obj.toString()); // TypeError: obj.toString is not a function
// obj → Object.prototype → null
// obj = {};와 동일하다.
obj = Object.create(Object.prototype);
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
// obj → Object.prototype → null
// obj = { x: 1 };와 동일하다.
obj = Object.create(Object.prototype, {
x: { value: 1, writable: true, enumerable: true, configurable: true }
});
// 위 코드는 다음과 동일하다.
// obj = Object.create(Object.prototype);
// obj.x = 1;
console.log(obj.x); // 1
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
const myProto = { x: 10 };
// 임의의 객체를 직접 상속받는다.
// obj → myProto → Object.prototype → null
obj = Object.create(myProto);
console.log(obj.x); // 10
console.log(Object.getPrototypeOf(obj) === myProto); // true
// 생성자 함수
function Person(name) {
this.name = name;
}
// obj → Person.prototype → Object.prototype → null
// obj = new Person('Lee')와 동일하다.
obj = Object.create(Person.prototype);
obj.name = 'Lee';
console.log(obj.name); // Lee
console.log(Object.getPrototypeOf(obj) === Person.prototype); // true
Object.create는 객체를 생성하면서 직접적으로 상속을 구현한다. new 연산자가 없어도 객체를 생성할 수 있고, 프로토타입을 지정하면서 객체를 생성할 수 있고, 객체리터럴에 의해 생성된 객체도 상속받을 수 있다.
const obj = Object.create(null); // 프로토타입 체인 종점
obj.a = 1;
console.log(Object.getPrototypeOf(obj) === null); // true
console.log(obj.hasOwnProperty('a'));
// TypeError: obj.hasOwnProperty is not a function
프로토타입 체인의 종점에 위치는 객체는 Object.prototype의 빌트인 메서드를 사용할 수 없다. 그래서 Object.prototype의 빌트인 메서드는 간접적으로 호출해야한다.
const obj = Object.create(null); // 프로토타입 체인 종점
obj.a = 1;
// Object.prototype의 빌트인 메서드는 객체로 직접 호출하지 않는다.
console.log(Object.prototype.hasOwnProperty.call(obj, 'a')); // true
7.2. 객체 리터럴 내부에서 __proto__에 의한 직접 상속
const myProto = { x: 10 };
// 객체 리터럴에 의해 객체를 생성하면서 프로토타입을 지정하여 직접 상속받을 수 있다.
const obj = {
y: 20,
// 객체를 직접 상속받는다.
// obj → myProto → Object.prototype → null
__proto__: myProto
};
/** 위 코드는 아래와 동일하다.
const obj = Object.create(myProto, {
y: { value: 20, writable: true, enumerable: true, configurable: true }
});
*/
console.log(obj.x, obj.y); // 10 20
console.log(Object.getPrototypeOf(obj) === myProto); // true
8. 정적 프로퍼티/메서드
정적(static) 프로퍼티/메서드는 생성자 함수로 인스턴스를 생성하지 않아도 참조/호출할 수 있다.
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`Hi! My name is ${this.name}`);
};
// 정적 프로퍼티
Person.staticProp = 'static prop';
// 정적 메서드
Person.staticMethod = function () {
console.log('staticMethod');
};
const me = new Person('april');
// 생성자 함수에 추가한 정적 프로퍼티/메서드는 생성자 함수로 참조/호출한다.
Person.staticMethod(); // staticMethod
// 정적 프로퍼티/메서드는 생성자 함수가 생성한 인스턴스로 참조/호출할 수 없다.
// 인스턴스로 참조/호출할 수 있는 프로퍼티/메서드는 프로토타입 체인 상에 존재해야 한다.
me.staticMethod(); // TypeError: me.staticMethod is not a function
정적 프로퍼티/메서드는 인스턴스 프로토타입 체인에 속한 객체의 프로퍼티/메서드가 아니므로 인스턴스로 접근할 수 없다.
// Object.create는 정적 메서드다.
const obj = Object.create({ name: 'Lee' });
// Object.prototype.hasOwnProperty는 프로토타입 메서드다.
obj.hasOwnProperty('name'); // false
Object.create 메서드는 Object 생성자 함수의 정적 메서드고 Object.prototype.hasOwnProperty메서드는 Object.prototype의 메서드다. 따라서 Object.create 메서드는 Object 생성자 함수가 생성한 객체로 호출할 수 없다. 하지만 Object.prototype.hasOwnProperty 메서드는 Object.prototype의 메서드이므로 객체가 호출할 수 있다.
참고: 모던 자바스크립트 Deep Dive
'Javascript' 카테고리의 다른 글
[Javascript] This에 대하여 (0) | 2023.03.25 |
---|---|
[Javascript] 엄격 모드(Strict mode) (0) | 2023.03.24 |
[Javascript] 프로퍼티 어트리뷰트 (0) | 2023.03.22 |
[Javascript] var와 let, const의 차이 (0) | 2023.03.21 |
[Javascript] 즉시 실행 함수(IIFE, Immediately Invoked Function Expression) (0) | 2023.03.20 |