9. 프로토타입의 교체
- 프로토타입은 임의의 다른 객체로 변경 가능
- 부모 객체인 프로토타입을 동적으로 변경할 수 있다
- 위 두 특징으로 인해 객체 간의 상속 관계를 동적으로 변경할 수 있다.
1. 생성자 함수에 의한 프로토타입의 교체
const Person = (function () {
function Person(name) {
this.name = name;
}
// ① 생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체
Person.prototype = {
sayHello() {
console.log(`Hi! My name is ${this.name}`);
}
};
return Person;
}());
const me = new Person('Lee');
①에서 Person.prototype에 객체 리터럴을 할당해서 Person 생성자 함수가 생성할 객체의 프로토타입을 객체 리터럴로 교체시켰다.
프로토타입으로 교체한 객체 리터럴에는 객체 리터럴로 선언되어 기존의 생성자함수 Person을 잃어버렸기 때문에 constructor 프로퍼티가 없다. 그렇기 때문에 me 객체의 생성자 함수를 검색하면 Person이 아닌 Object가 나온다.
// 프로토타입을 교체하면 constructor 프로퍼티와 생성자 함수 간의 연결이 파괴된다.
console.log(me.constructor === Person); // false
// 프로토타입 체인을 따라 Object.prototype의 constructor 프로퍼티가 검색된다.
console.log(me.constructor === Object); // true
이렇게 프로토타입을 교체하면 constructor 프로퍼티와 생성자 함수 간의 연결이 파괴된다.
const Person = (function () {
function Person(name) {
this.name = name;
}
// 생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체
Person.prototype = {
// constructor 프로퍼티와 생성자 함수 간의 연결을 설정
constructor: Person,
sayHello() {
console.log(`Hi! My name is ${this.name}`);
}
};
return Person;
}());
const me = new Person('Lee');
// constructor 프로퍼티가 생성자 함수를 가리킨다.
console.log(me.constructor === Person); // true
console.log(me.constructor === Object); // false
하지만 교체한 객체 리터럴에 constructor 프로퍼티를 추가하여 constructor 프로퍼티와 생성자 함수간의 연결을 간단히 되살릴 수 있다.
2. 인스턴스에 의한 프로토타입의 교체
인스턴스의 __proto__ 접근자 프로퍼티와 Object.PrototypeOf 메서드를 통해 프로토 타입을 교체할 수 있다.
※ __proto__ 접근자 프로퍼티를 통해 프로토타입을 교체하는 것은 이미 생성된 객체의 프로토타입을 교체하는 것
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
// 프로토타입으로 교체할 객체
const parent = {
sayHello() {
console.log(`Hi! My name is ${this.name}`);
}
};
// ① me 객체의 프로토타입을 parent 객체로 교체한다.
Object.setPrototypeOf(me, parent);
// 위 코드는 아래의 코드와 동일하게 동작한다.
// me.__proto__ = parent;
me.sayHello(); // Hi! My name is Lee
①에서 me 객체의 프로토타입을 parent 객체로 교체했다.
위 생성자 함수에 의한 프로토타입의 교체와 마찬가지로 프로토타입으로 교체한 객체에는 constructor 프로퍼티가 없으므로 constructor 프로퍼티와 생성자 함수 간의 연결이 파괴된다.
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
// 프로토타입으로 교체할 객체
const parent = {
// constructor 프로퍼티와 생성자 함수 간의 연결을 설정
constructor: Person,
sayHello() {
console.log(`Hi! My name is ${this.name}`);
}
};
// 생성자 함수의 prototype 프로퍼티와 프로토타입 간의 연결을 설정
Person.prototype = parent;
// me 객체의 프로토타입을 parent 객체로 교체한다.
Object.setPrototypeOf(me, parent);
// 위 코드는 아래의 코드와 동일하게 동작한다.
// me.__proto__ = parent;
me.sayHello(); // Hi! My name is Lee
// constructor 프로퍼티가 생성자 함수를 가리킨다.
console.log(me.constructor === Person); // true
console.log(me.constructor === Object); // false
// 생성자 함수의 prototype 프로퍼티가 교체된 프로토타입을 가리킨다.
console.log(Person.prototype === Object.getPrototypeOf(me)); // true
이렇게 객체 리터럴에 constructor 프로퍼티를 추가하고 생성자 함수의 prototype 프로퍼티를 재설정하여 파괴된 생성자 함수와 프로토타입 간의 연결을 되살릴 수 있다.
생성자 함수 및 인스턴스에 의한 프로토타입 교체의 서로 다른 차이점
프로토타입 교체를 통해 객체 간의 상속 관계를 동적으로 변경하는 것은 꽤나 번거롭기 때문에 프로토타입은 직접 교체하지 않는 것이 좋다.
상속 관계를 인위적으로 설정하려면 직접 상속을 통해 구현하거나 클래스를 통해서 구현하는 것이 효과적이다.
10. instanceof 연산자
객체 instanceof 생성자 함수
// 생성자 함수
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
// Person.prototype이 me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다.
console.log(me instanceof Person); // true
// Object.prototype이 me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다.
console.log(me instanceof Object); // true
우변의 생성자 함수의 prototype에 바인딩된 객체가 좌변의 객체의 프로토타입 체인 상에 존재하면 true, 그렇지 않을 경우는 false로 평가된다.
// 생성자 함수
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
// 프로토타입으로 교체할 객체
const parent = {};
// 프로토타입의 교체
Object.setPrototypeOf(me, parent);
// Person 생성자 함수와 parent 객체는 연결되어 있지 않다.
console.log(Person.prototype === parent); // false
console.log(parent.constructor === Person); // false
// parent 객체를 Person 생성자 함수의 prototype 프로퍼티에 바인딩한다.
Person.prototype = parent;
// Person.prototype이 me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다.
console.log(me instanceof Person); // true
// Object.prototype이 me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다.
console.log(me instanceof Object); // true
instanceof 연산자는 프로토타입의 constructor 프로퍼티가 가리키는 생성자 함수를 찾는 것이 아닌 생성자 함수의 prototype에 바인딩된 객체가 프로토타입 체인상에 존재하는지 확인
me instanceof Person의 경우 me 객체의 프로토타입 체인 상에 Person.prototype이 바인딩된 객체가 존재하는지 확인
me instanceof Object의 경우 me 객체의 프로토타입 체인 상에 Object.prototype이 바인딩된 객체가 존재하는지 확인
결국, 생성자 함수에 의해 프로토타입이 교체되어 constructor 프로퍼티와 생성자 함수 간의 연결이 파괴되어도 생성자 함수의 prototype 프로퍼티와 프로토타입 간의 연결은 파괴되지 않으므로 instanceof는 아무런 영향을 받지 않는다.
11. 직접 상속
1. Object.create에 의한 상속
Object.create(prototype[, propertiesObject])
// 첫 번째 매개변수 : 생성할 객체의 프토토타입으로 지정할 객체
// 두 번째 매개변수 : 생성할 객체의 프로퍼티 키와 프로퍼티 디스크립터로 객체로 이뤄진 객체
- Object.create 메서드는 명시적으로 프로토타입을 지정하여 새로운 객체를 생성
- Object.create 메서드도 다른 객체 생성 방식과 마찬가지로 추상 연산 OrdinaryObjectCreate를 호출
// 프로토타입이 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 연산자가 없이도 객체를 생성할 수 있다.
- 프로토타입을 지정하면서 객체를 생성할 수 있다.
- 객체 리터럴에 의해 생성된 객체도 상속받을 수 있다.
2. 객체 리터럴 내부에서 __proto__에 의한 직접 상속
Object.create의 두 번째 인자로 프로퍼티를 정의하는 것이 번거로운데, ES6에서는 객체 리터럴 내부에서 __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
12. 정적 프로퍼티/메서드
정적 프로퍼티/메서드 : 생성자 함수로 인스턴스를 생성하지 않아도 참조/호출할 수 있는 프로퍼티/메서드
// 생성자 함수
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('Lee');
// 생성자 함수에 추가한 정적 프로퍼티/메서드는 생성자 함수로 참조/호출한다.
Person.staticMethod(); // staticMethod
// 정적 프로퍼티/메서드는 생성자 함수가 생성한 인스턴스로 참조/호출할 수 없다.
// 인스턴스로 참조/호출할 수 있는 프로퍼티/메서드는 프로토타입 체인 상에 존재해야 한다.
me.staticMethod(); // TypeError: me.staticMethod is not a function
위 예제에서 Person 생성자 함수는 객체이므로 자신의 프로퍼티/메서드를 소유할 수 있다. 이때 Person 생성자 함수 객체가 소유한 프로퍼티/메서드를 정적 프로퍼티/메서드라고 하는데 정적 프로퍼티와 메서드는 생성자 함수가 생성한 인스턴스로 참조나 호출할 수 없다. (인스턴스의 프로토타입 체인에 속한 객체의 프로퍼티/메서드가 아니기 때문)
13. 프로퍼티 존재 확인
1. in 연산자
in 연산자 : 객체 내에 특정 프로퍼티가 존재하는지 여부를 확인(boolean으로 반환)
const person = {
name: 'Lee',
address: 'Seoul'
};
// person 객체에 name 프로퍼티가 존재한다.
console.log('name' in person); // true
// person 객체에 address 프로퍼티가 존재한다.
console.log('address' in person); // true
// person 객체에 age 프로퍼티가 존재하지 않는다.
console.log('age' in person); // false
console.log('toString' in person); // true
in 연산자는 확인 대상 객체의 프로퍼티뿐만 아니라 객체가 상속받은 모든 프로토타입의 프로퍼티를 확인하므로 주의가 필요하다!
in 연산자 대신 ES6에 도입된 Reflect.has 메서드도 사용할 수 있다.(in 연산자와 동일하게 동작)
const person = { name: 'Lee' };
console.log(Reflect.has(person, 'name')); // true
console.log(Reflect.has(person, 'toString')); // true
2. Object.prototype.hasOwnProperty 메서드
Object.prototype.hasOwnProperty는 객체 고유의 프로퍼티 키인 경우에만 true를 반환하고, 상속받은 프로퍼티 키인 경우는 false를 반환한다.
console.log(person.hasOwnProperty('name')); // true
console.log(person.hasOwnProperty('age')); // false
console.log(person.hasOwnProperty('toString')); // false
14. 프로퍼티 열거
1. for...in 문
객체의 프로토타입 체인 상에 존재하는 모든 프로토타입의 프로퍼티 중에서 프로퍼티 어트리뷰트 [[Enumerable]]의 값이 true인 프로퍼티를 순회하며 열거
for(변수선언문 in 객체) {...}
const person = {
name: 'Lee',
address: 'Seoul',
__proto__: { age: 20 }
};
for (const key in person) {
console.log(key + ': ' + person[key]);
}
// name: Lee
// address: Seoul
// age: 20
- 프로퍼티 키가 Symbol인 프로퍼티는 열거하지 않는다.
- for... in문은 프로퍼티를 열거할 때 순서를 보장하지 않는다.
2. Object.keys/values/entries 메서드
객체 자신의 고유 프로퍼티만 열거하기 위해서는 for...in 문을 사용하는 것보다 Object.keys/values/entries 메서드를 이용하는 것이 더 좋다.
- Object.keys 메서드 : 객체 자신의 열거 가능한 프로퍼티 키를 배열로 반환
const person = { name: 'Lee', address: 'Seoul', __proto__: { age: 20 } }; console.log(Object.keys(person)); // ["name", "address"]
- Object.value 메서드 : 객체 자신의 열거 가능한 프로퍼티 프로퍼티 값을 배열로 반환(ES8에 도입)
console.log(Object.values(person)); // ["Lee", "Seoul"]
- Object.entries 메서드 : 객체 자신의 열거 가능한 프로퍼티 키와 값의 쌍의 배열을 배열로 반환(ES8에 도입)
console.log(Object.entries(person)); // [["name", "Lee"], ["address", "Seoul"]] Object.entries(person).forEach(([key, value]) => console.log(key, value)); /* name Lee address Seoul */
'자바스크립트' 카테고리의 다른 글
[모던자바스크립트 Deep Dive] 21. 빌트인 객체 (0) | 2022.02.05 |
---|---|
[모던자바스크립트 Deep Dive] 20. strict mode (0) | 2022.01.18 |
[모던자바스크립트 Deep Dive] 19. 프로토타입(2) (0) | 2022.01.10 |
[모던자바스크립트 Deep Dive] 19. 프로토타입(1) (0) | 2022.01.03 |
[모던자바스크립트 Deep Dive] 18. 함수와 일급 객체 (0) | 2021.12.22 |