Javascript/GMA(2302~)
23.04.24 자바스크립트 *생성자 함수와 프로토타입 객체 활용
hyerin1201
2023. 4. 25. 13:48
// 프로토타입이란?
// 생성자 함수 생성
const Book = function(title, pages, done) {
this.title = title;
this.pages = pages;
this.done = done;
this.finish = function() {
let str = "";
this.done == false ? str = "읽는 중" : str = "완독";
return str;
}
}
const book1 = new Book("javascript", 650, false); // book1 = Book 생성자 함수로 만든 인스턴스 객체
// book1
book1
Book {title: 'javascript', pages: 650, done: false, finish: ƒ}
book1.finish();
'읽는 중'
book1.__proto__;
{constructor: ƒ}
constructor: ƒ (title, pages, done)
[[Prototype]]: Object
// Book 의 프로토타입 확인
Book.prototype
{constructor: ƒ}
constructor: ƒ (title, pages, done)
[[Prototype]]: Object
Object > Book > book1
book1.__proto__; // 인스턴스객체의 프로토타입을 확인할때
Book.prototype; // 생성자 함수의 프로토타입을 확인할때
// 프로토타입 프로퍼티를 활용하여 생성자 함수안에 메서드를 추가 생성할 수 있다.
prototype 프로퍼티를 활용해서 생성자 함수안에 메서드를 추가 생성하기
const Book = function(title, pages, done) { //Book 이라는 생성자 함수 생성
this.title = title;
this.pages = pages;
this.done = done;
}
Book.prototype.finish = function() { //프로토타입 프로퍼티 활용하여 새로운 매서드 추가
let str = "";
this.done == false ? str = "읽는 중" : str = "완독";
return str
}
let nbook1 = new Book("javascript", 650, true);
유사한, 동일한 프로퍼티 혹은 메서드를 가지고 있는객체를 대량으로 생산하고 싶어서
만약 100% 똑같지는 않지만 새로운 버전의 생성자 함수가 필요하다면?
function Book(title, price) {
this.title = title;
this.price = price;
}
Book.prototype.buy = function(){
console.log(`${this.title}을 ${this.price}원에 구매하였습니다`);
}
const book1 = new Book("ABCDE", 10000);
//만약에 교재정보를 추가로 담는 또다른 생성자 함수가 필요하다면? --> 생성자 함수의 복제가 필요하다.
function Textbook(title, price, major) {
Book.call(this, title, price)//기존에 만든 생성자 함수에서 값을 호출할때
this.major = major;
}
Textbook.prototype.buyTextbook = function() {
console.log(`${this.major} 전공서적, ${this.title}을 구매했습니다.`)
}
const book2 = new Textbook("알고리즘", 5000, "컴퓨터공학");
// book2;
// Textbook {title: '알고리즘', price: 5000, major: '컴퓨터공학'}
// book2.buyTextbook();
// 컴퓨터공학 전공서적, 알고리즘을 구매했습니다.
// book2.buy(); 는 쓸수가없다. 쓰고싶다면?
Object.setPrototypeOf(Textbook.prototype, Book.prototype); // 자녀객체 - 부모객체
// 생성자 함수의 상속. (메서드까지 포함한 모든내용을 상속시킨다.);
클래스버전 (클랙스는 Object.setPrototypeOf 를 쓰지 않아도 됨)
class BookC {
constructor(title, price) {
this.title = title;
this.price = price;
}
buy() {
console.log(`${this.title}을 ${this.price}원에 구매하였습니다`);
}
}
const book1 = new BookC("자료구조", 15000);
class TextbookC extends BookC {
constructor(title, price, major) {
super(title,price);
this.major = major;
}
buyTextbook() {
console.log(`${this.major} 전공서적, ${this.title}을 구매했습니다.`)
}
}
const book2 = new TextbookC("인공지능", 5000, "컴퓨터공학");
*생성자 함수를 활용한 객체 생성방법 : 고전적인 방법
2015년 ES6 버전: 클래스 객체 생성방법