function storage() {
this.dataScore = {};
}
// storage() 생성자 함수를 정의.
// 이 함수는 내부적으로 dataScore를 가지고 빈 객체를 할당한다.
storage.prototype.put = function(key, data) {
this.dataStore[key] = data;
}
// storage 의 프로토타입 객체에 put 메소드를 추가한다.
// put 메소드는 key 와 data 를 전달받아 dataStore 객체에 프로퍼티를 만든다.
storage.prototype.getData = function(key) {
return this.dataStore[key];
}
// getData 메소드도 만드는데, 그 기능은 key 를 입력받아서
// dataStore 객체에서 그 키의 값을 불러와 리턴해 주는 것.
const productStorage = new Storage();
productStorage.put('id001', {name: '키보드', price: 2000});
console.log(productStorage.getData('id001'));
// productStorage 라는 인스턴스를 만든다.
// 이 인스턴스는 store() 의 프로토타입을 상속받으므로 put,getData 메소드 사용가능.
// 프로토타입에 있는 put 메소드를 이용해 id001 프로퍼티를 dataStore 에 넣는다.
// 역시 프로토타입에 있는 getData 메소드를 이용해 id001 키의 값을 불러와 콘솔에 출력한다.
// 여기까지 한 호흡 끝. 아래는 그 다음 호흡!
function RemovableStrage() {
Storage.call(this);
}
// Remo... 생성자 함수를 정의.
// 이 때 Stogage 함수를 호출하면서 this를 전달하는데
// 이렇게 되면 Storage 생성자 함수가 호출되면서 Remo... 생성자 함수의 this에
// Storage 생성자 함수에서 정의한 대로 dataStore 가 속성으로 추가된다.
RemovableStrage.prototype = Object.create(Storage.prototype);
RemovableStrage.prototype.removeAll = function() {
this.dataStore = {};
}
// Object.create 메소드는 주어진 인자를 __proto__ 에 연결한 새로운 객체를 반환.
// Re...prototype 에 Object.create(Storage.prototype) 를 할당하면
// Storage 함수의 프로토타입 객체가 Re... 함수의 프로토타입 객체의 __proto__에 할당된다.
// 이렇게 두 프로토타입이 상속관계를 형성하게 된다.
// 그리고 Re... 생성자 함수의 프로토타입 객체에 removeAll 메소드를 추가한다.
const productStorage2 = new RemovableStrage();
productStorage2.put('id001', {name: '키보드', price: 2000});
productStorage2.removeAll();
const item2 = productStorage2.getdata('id001');
console.log(item2); // removeAll() 로 객체를 비웠으니까 undefined 가 출력된다.
// Re... 생성자 함수에 의해 만들어지는 인스턴스들은
// 메소드를 Re... 생성자 함수의 프로토타입에서 먼저 찾고,
// 거기에 없으면 Storage 생성자 함수의 프로토타입에서 찾고,
// 나아가 Object.prototype 에서까지 찾게 된다.
// 이렇게 프로토타입 객체가 서로 연결되어 있다 하여 이를 프로토타입 체인이라고 한다.