프로토타입과 class 에 대해서 알아보자!
프로토타입과 class란?
JavaScript 는 클래스라는 개념이 없습니다
그래서 기존의 객체를 복사하여 새로운 객체를 생성하는 프로토타입 기반의 언어입니다.
프로타타입 기반 언어는 객체 원형인 프로토타입을 이용하여 새로운 객체를 만들어냅니다.
이렇게 생성된 객체 역시 또 다른 객체의 원형이 될 수 있으며 프로토타입은 객체를 확장하고 객체 지향적인 프로그래밍 ( OOP )을 할수있게 해줍니다
JavaScript 는 생성자함수와 new 연산자를 통해 인스턴스를 생성할수 있으며 생성자 함수로부터 만들어진 객체는 그 생성자 함수의 프로토타입 ( Prototype ) 객체를 상속합니다
즉 모든 인스턴스는 해당 생성자 함수의 프로토타입 객체의 속성과 메소드를 사용할 수 있습니다
Javascript 의 모든 함수 prototype 속성으로 프로토타입 객체를 가집니다
__proto__ 속성은 해당 객체를 생성한 생성자 함수의 prototype 객체를 가리킵니다
그래서 생성자 함수를 통해서 타입을 정의할 수 있습니다
1. function Storage() {
2. this.dataStore = {};
3. }
4. Storage.prototype.put = function(key, data){
5. this.dataStore[key] = data;
6. }
7. Storage.prototype.getData = function(key) {
8. return this.dataStore[key];
9. }
10.
11. const productStorage = new Storage();
12. productStorage.put('id001',{name:'키보드', price: 2000});
13. console.log(productStorage.getData('id001'));
14.
15. function RemovableStorage() {
16. Storage.call(this);
17. }
18. RemovableStorage.prototype = Object.create(Storage.prototype);
19. RemovableStorage.prototype.removeAll = function() {
20. this.dataStore = {}
21. }
22. const productStorage2 = new RemovableStorage();
23. productStorage2.put('id001', {name:'키보드',price: 2000});
24. productStorage2.removeAll();
25. const item2 = productStorage2.getData('id001');
26. console.log(item2);

1~3. Storage 생성자 함수를 정의합니다.
내부 속성으로 dataStore를 가지고 빈 객체를 할당합니다.
4~6. Storage 생성자 함수의 프로토타입 객체에 put 메소드를 추가합니다.
put 메소드는 주어진 키에 해당하는 값을 dataStore 속성에 할당합니다.
7~9. Storage 생성자 함수의 프로톹타입 객체에 getData메소드를 추가합니다.
getData 메소드는 매개변수의 값을 키로 해서 dataStore 속성에서 찾아 반환합니다.
11~12. Storage 타입의 인스턴스를 생산하면 인스턴스는 해당 생성자 함수의 프로토타입을 상속합니다.
그래서 Storage 생성자 함수의 프로토타입에 정의된 메소드들을 해당 인스턴스들은 사용할 수 있습니다.
15~17. RemovableStorage 생성자 함수를 정의합니다.
이때 Storage 함수를 호출하면서 this를 전달하는데 이렇게 되면 Storage 생성자 함수가 호출되면서
RemovableStorage 생성자 함수의 this에 Storage 생성자 함수에서 정의한 대로 dataStore가 속성으로 추가됩니다.
18~21. Object.create 메소드는 주어진 인자를 __proto__에 연결한 새로운 객체를 반환합니다.
Object.create를 이용하면 간단히 상속 관계를 형성할 수 있습니다.
RemovableStorage.prototype 에 Object.create(Storage.prototype) 를 할당하면 Storage 함수의
프로토타입 객체가 RemovableStorage 함수의 프로토타입 객체의 __proto__에 할당됩니다.
그러면 두 프로토타입이 상속 관계를 형성하게 됩니다.
그리고 RemovableStorage 생성자 함수의 프로토타입 객체에 removeAll 메소드를 추가합니다.
22~26 RemovableStorage 생성자 함수에 의해 만들어지는 인스턴스들은 내부에 없는 메소드를 RemovableStorage생성자 함수의 프로토타입에서 먼저 찾고.
없으면 Storage 생성자 함수의 프로토타입에서 찾게 됩니다.
나아가 Object.prototype에서 까지 찾게 됩니다.
이렇게 프로토타입 객체가 서로 연결되어 있다 하여 이를 프로토타입 체인이라고도 합니다.
'코드스테이츠 시작후 정리' 카테고리의 다른 글
| 코드스테이츠 블로깅 일곱번째 프로토타입 체인 (0) | 2022.07.25 |
|---|---|
| Section1 회고 출발이 좋은가? (0) | 2022.07.23 |
| 코드스테이츠 블로깅 다섯번째 객체 지향 프로그래밍 ( OOP ) (0) | 2022.07.22 |
| 코드스테이츠 블로깅 네번째 class 와 instance (0) | 2022.07.22 |
| 코드스테이츠 블로깅 세번째 JavaScript Koans (0) | 2022.07.13 |