자바스크립트
= 여러 개의 독립적 단위, 즉 객체의 집합으로 프로그램을 표현하려는 프로그래밍 패러다임
// 생성자 함수
function Circle(radius) {
this.radius = radius;
this.getArea = function () {
return Math.PI * this.radius ** 2;
};
}
const circle1 = new Circle(1);
const circle2 = new Circle(2);
console.log(circle1.getArea === circle2.getArea); // false
Circle 생성자 함수는 인스턴스를 생성할 때마다 getArea 메서드를 중복 생성하고 모든 인스턴스가 중복 소유함
// 생성자 함수
function Circle(radius) {
this.radius = radius;
}
Circle.prototype.getArea = function () {
return Math.PI * this.radius ** 2;
};
const circle1 = new Circle(1);
const circle2 = new Circle(2);
// Circle 생성자 함수가 생성하는 모든 인스턴스는 하나의 getArea 메서드를 공유
console.log(circle1.getArea === circle2.getArea); // true
getArea 메서드는 모든 인스턴스가 동일한 내용의 메서드를 사용하므로 단 하나만 생성하여 모든 인스턴스가 공유해서 사용하는 것이 바람직함
→ 자신의 상태를 나타내는 radius 프로퍼티만 개별적으로 소유하고 내용이 동일한 메서드는 상속을 통해 공유하여 사용
1. __prototype__는 접근자 프로퍼티
모든 객체는 __prototype__ 접근자 프로퍼티를 통해 자신의 프로토타입, 즉 [[Prototype]] 내부 슬롯에 간접적으로 접근 가능
2. __prototype__ 접근자 프로퍼티는 상속을 통해 사용됨
모든 객체는 상속을 통해 Object.prototype.__proto__ 접근자 프로퍼티 사용 가능
3. __prototype__ 접근자 프로퍼티를 통해 프로토타입에 접근하는 이유
4. __prototype__ 접근자 프로퍼티를 코드 내에서 직접 사용하는 것은 권장하지 않음
프로토타입의 참조를 취득하고 싶은 경우에는 Object.getPrototypeOf 메서드를 사용하고, 프로토타입을 교체하고 싶은 경우에는 Object.setPrototypeOf 메서드를 사용할 것을 권장
함수 객체만이 소유하는 prototype 프로퍼티
= 생성자 함수가 생성할 인스턴스의 프로토타입
// 함수 객체는 prototype 프로퍼티를 소유
(function () {} ).hasOwnProperty('prototype'); → true
// 일반 객체는 prototype 프로퍼티를 소유하지 않음
({}).hasOwnProterty('prototype'); → false
| 구분 | 소유 | 값 | 사용 주체 | 사용 목적 |
|---|---|---|---|---|
| __prototype__ | 모든 객체 | 프로토타입의 참조 | 모든 객체 | 객체가 자신의 프로토타입에 접근 또는 교체하기 위해 사용 |
| prototype 프로퍼티 | constructor | 프로토타입의 참조 | 생성자 함수 | 생성자 함수가 자신이 생성할 객체의 프로토타입을 할당하기 위해 사용 |
constructor 프로퍼티 = prototype 프로퍼티로 자신을 참조하고 있는 생성자 함수
// 생성자 함수
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
// me 객체의 생성자 함수는 Person임
console.log(me.constructor === Person); // true
me 객체의 프로토타입의 constructor 프로퍼티를 통해 생성자 함수와 연결됨
→ me 객체는 프로토타입인 Person.prototype의 constructor 프로퍼티를 상속받아 사용 가능
// obj 객체는 Object 생성자 함수로 생성한 객체가 아니라 객체 리터럴로 생성했음
const obj = {};
// 하지만 obj 객체의 생성자 함수는 Object 생성자 함수임
console.log(obj.constructor === Object); // true
// 인수가 전달되지 않았을 때 추상 연산 OrdinaryObjectCreate를 호출하여 빈 객체를 생성
let obj = new Object();
console.log(obj); // {}
// new.target이 undefined나 Object가 아닌 경우
// 인스턴스 → Foo.prototype → Object.prototype 순으로 프로토타입 체인이 생성됨
class Foo extends Object {}
new Foo(); // Foo {}
// 인수가 전달된 경우에는 인수를 객체로 변환
// Number 객체 생성
obj = new Object(123);
console.log(obj); // Number {123}
// String 객체 생성
obj = new Object('123');
console.log(obj); // String {"123"}
객체 리터럴에 의해 생성된 객체는 Object 생성자 함수가 생성한 객체가 아님
프로토타입은 생성자 함수가 생성되는 시점에 더불어 생성됨
(생성자 함수는 사용자 정의 생성자 함수와 빌트인 생성자 함수로 구분)
// 화살표 함수는 non-constructor
const Person = name => {
this.name = name;
};
// non-constructor는 프로토타입이 생성되지 않음
console.log(Person.prototype); // undefined
const obj = { x: 1 };
// 객체 리터럴에 의해 생성된 obj 객체는 Object.prototype을 상속받음
console.log(obj.consturctor === Object); // true
console.log(obj.hasOwnProperty('x')); // true
const obj = new Object();
obj.x = 1;
// Object 생성자 함수에 의해 생성된 obj 객체는 Object.prototype을 상속받음
console.log(obj.constructor === Object); // true
console.log(obj.hasOwnProperty('x')); // true
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`Hi! My name is ${this.name}`);
};
const me = new Person('Lee');
const you = new Person('Kim');
me.sayHello(); // Hi! My name is Lee
you.sayHello(); // Hi! My name is Kim
const Person = (function () {
// 생성자 함수
function Person(name) {
this.name = name;
}
// 프로토타입 메서드
Person.prototype.sayHello = function () {
console.log(`Hi! My name is ${this.name}`);
};
// 생성자 함수를 반환
return Person;
}());
const me = new Person('Lee');
me.sayHello = function () {
console.log(`Hey! My name is ${this.name}`);
};
// 인스턴스 메서드가 호출됨
// 프로토타입 메서드는 인스턴스 메서드에 의해 가려짐
me.sayHello(); // Hey! My name is Lee
// 인스턴스 메서드를 삭제
delete me.sayHello;
// 인스턴스에는 sayHello 메서드가 없으므로 프로토타입 메서드가 호출됨
me.sayHello(); // Hi! My name is Lee
// 프로토타입 체인을 통해 프로토타입 메서드가 삭제되지 않음
delete me.sayHello;
// 프로토타입 메서드가 호출됨
me.sayHello(); // Hi! My name is Lee
delete Person.prototype.sayHello;
me.sayHello(); // TypeError: me.sayHello is not a function
프로토타입은 임의의 다른 객체로 변경할 수 있음
= 부모 객체인 프로토타입 동적 변경 가능
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); // true
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
객체 instanceof 생성자 함수
우변의 생성자 함수의 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 객체의 프로토타입 체인 상에 존재함
console.log(me instanceof Person); // true
// Object.prototype이 me 객체의 프로토타입 체인 상에 존재함
console.log(me instanceof Object); // true
Object.create 메서드는 첫번째 매개변수에 전달한 객체의 프로토타입 체인에 속하는 객체를 생성
→ 객체를 생성하면서 직접적으로 상속을 구현하는 것
const myProto = { x: 10 };
const obj = {
y: 20,
__proto__: myProto
};
console.log(obj.x, obj.y); // 10 20
console.log(Object.getPrototypeOf(obj) === myProto); // true
__proto__ 접근자 프로퍼티를 사용하여 직접 상속 구현 가능
= 생성자 함수로 인스턴스를 생성하지 않아도 참조/호출이 가능한 프로퍼티/메서드
(생성자 함수가 생성한 인스턴스로 참조/호출 불가능)
function Foo() {}
// 프로토타입 메서드
// this를 참조하지 않는 프로토타입 메서드는
// 정적 메서드로 변경하여도 동일한 효과를 얻음
Foo.prototype.x = function() {
console.log('x');
};
const foo = new Foo();
// 프로토타입 메서드를 호출하려면 인스턴스를 생성해야 함
foo.x(); // x
// 정적 메서드
Foo.x = function() {
console.log('x');
};
// 정적 메서드는 인승텅ㄴ스를 생성하지 않아도 호출 가능
Foo.x(); // x