-
Prototype과 JavaScript에서 Object를 생성하는 방법개념정리 2021. 1. 14. 14:44
Prototype?
1. 자바스크립트는 프로토타입 기반의 언어
2. Prototype Link 와 Prototype Object를 합친 용어
3. 함수가 정의될 때
3-1. 함수에 Constructor 자격 부여
3-2. Prototype Object 생성 및 연결
4.Prototype Chain?
: proto속성을 통해 상위 프로토타입과 연결되어 있는 형태
4-1. 자식Prototype의 가지고 있지 않은 속성을 찾을때까지 부모Prototype을 탐색한다.
4-2. 최상위 Object Prototype까지 도달했는데도 못찾을 경우에는 undefined 리턴한다.
prototype vs __proto__
자바스크립트에센 함수도 객체로 취급한다

출처 생활코딩 1. 함수를 만든다
2. Function 과 Prototype 을 만든다
3. Function 과 Prototype은 서로 연관되어 있다
4. Function 안에는 prototype이라는 property가 자동 생성된다.
5. Prototype 안에는 constructor이라는 property가 자동 생성된다.
6. prototype 은 Prototype 을 가리킨다
7. constructor 은 Function 을 가리킨다
8. 여기서 new 키워드로 instance 을 생성할 시
9. instance 안에는 __proto__가 자동 생성된다.
10. __proto__ 는 Prototype을 가리킨다
Functional (인스턴스를 생성할 때마다 모든 메소드를 메모리에 추가한다)👇
let Car = function(position = 0) { // undefined 일때 0이 들어감
let status = {};
status.position = position;
status.move = function() {
this.position++;
}
return status;
}
let car = Car();
car.move();
console.log(car.position);
Functional Shared
let extend = function(to, from) {
for (let key in from) {
to[key] = from[key];
}
};
const person = {};
person.say = function(hi) {
this.say = hi;
}
const Car = function() {
const status = {};
status.name = 'tesla';
status.move = function() {
console.log('앞으로 이동');
}
extend(status, person);
return status;
}
let car = Car();
console.log(car.name);
console.log(car.move());
console.log(car.say('hello');
Prototypal
let someMethods = {};
someMethods.move = function() {
this.position++; // 매소드 만들기
}
let Car = function(position) {
let someInstance = Object.create(someMethods); // 메소드 복사후 만들기
someInstance.position = position;
return someInstance;
}
let car = Car(10);
car.move();
console.log(car); // {position: 11}
pseudoclassical
let Car = function(position) {
this.position = position;
}
Car.prototype.move = function() {
this.position++;
}
let car = new Car(5);
car.move();
console.log(car.position);
'개념정리' 카테고리의 다른 글
Data structure (Linked list, Hash Table) (0) 2021.01.23 Data structure (stack, queue) (0) 2021.01.19 Object Oriented Programming (0) 2021.01.14 this 와 call, apply, bind 키워드 (0) 2021.01.14 map(), filter(), reduce() 에 대하여 (0) 2021.01.12