
프로토타입은 초호기다!
모델의 청사진을 만들 때 쓰는 원형 객체(Original form)
Prototype Object는 기본적인 속성으로 constructor과 __proto__를 가진다.
| constructor | Prototype Object와 함께 생성되었던 함수를 가리킨다. |
| this | 함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context new 키워드로 인스턴스를 생성할 때는 해당 instance가 this가 된다. |
__proto__ (Prototype link) | 객체가 생성될 때 조상이었던 함수의 Prototype Object를 가리킨다. |
function Cat() {}
Cat.prototype.feet = 4;
Cat.prototype.tail = 1;
const Moo = new Cat();
const Raegi = new Cat();
__proto속성 덕분에Moo에는feet이라는 속성이 없지만,Moo.feet을 실행하면 4라는 값을 참조한다.
Moo 객체는 feet을 직접 가지고 있지 않기 때문에 feet속성을 찾을 때까지 상위 프로토타입을 탐색한다. (못 찾을 경우 undefined를 리턴한다.

__proto__속성을 통해 상위 프로토타입과 연결되어있는 형태
데이터를 만들기 위해서 추상화를 거쳐 속성과 행위를 변수와 메소드로 정의한 것
constructor를 가지고 있다.
function Cat(name, color, age, sound) { // Cat: class
this.name = name; // this 객체: 여기서는
this.color = color;
this.age = age;
this.sound = sound;
} // 생성자 함수(constructor)
Cat.prototype.cry = function() {
console.log(`${this.name}이 "${this.sound}"하고 운다.`);
}
let Yatong = new Cat('야통','grey','3','이얏호응');
Yatong.color; //'grey'
Yatong.cry(); // '야통이 "이얏호응"하고 운다.'
constructor:class내에서 객체를 생성하고 초기화하기 위한 특별한 메서드
클래스는 실행 시에 인스턴스될 수 있는 type을 정의하는 반면 프로토타입은 객체 인스턴스 그 자체다.
에반게리온의 예시로 들면...
프로토타입: 초호기

인스턴스: 2호기, 3호기...

클래스: 에바를 만드는 데 필요한 구성요소(LCL, AT필드...)를 포함한 설계도
클래스에서 정의된 속성과 행위를 담은 실제 메모리상에 할당된 데이터
인스턴스를 만드는 패턴
함수를 이용해서 Class를 만드는 방식
funcitonal 방식은 인스턴스를 생성할 때마다 모든 메소드를 someInstance에게 할당한다. 따라서 각각의 인스턴스들이 메소드의 수만큼 메모리를 더 차지하게 된다.
const Cat = function() {
const catInstance = {};
catInstance.age = 0;
catInstance.old = function() {
this.age += 1;
}
return catInstance;
};
const Yatong = Cat();
const Marilyn = Cat();
Yatong.old(); // console.log(Yatong.age) => 1
const Cat = function(age) {
const catInstance = {};
catInstance.age = age;
catInstance.old = function() {
this.age += 1;
}
return catInstance;
};
Functional Shared 방식을 사용할 경우, someMethods라는 객체에 있는 메소드들의 메모리 주소만을 참조하기때문에 메모리 효율이 좋아진다.
const extend = function(to, from) {
for (let key in from) {
to[key] = from[key];
}
};
const someMethods = {};
someMethods.old = function() {
this.age += 1;
};
const Car = function(age) {
const catInstance = {
age: age,
};
extend(catInstance, someMethods);
return catInstance;
};
const someMethods = {};
someMethods.old = function() {
this.age += 1;
};
const Cat = function(age) {
const catInstance = Object.create(someMethods); //
catInstance.age = age;
return catInstance;
};
const Yatong = Cat(3);
const Marilyn = Cat(2)
Object.create는 특정 객체를 프로토타입으로 하는 객체를 생성해주는 함수 (공식문서)
1) 코드를 작성한다.
const Cat = function(age) {
this.age = age;
};
Cat.prototype.old = function() { // 메소드를 프로토타입으로 만든다. ```Object.create```
this.age += 1;
};
3) 인스턴스를 만들 때마다 new operator를 붙인다.
const Yatong = new Cat(3);
const Marilyn = new Cat(2)