JavaScript
[JS] 인스턴스란 대체 뭘까?
YoHaYo
2023. 9. 13. 13:05
728x90
반응형
객체 지향 프로그래밍 패러다임을 따른다는 것은 하나의 모델이 되는 청사진(blueprint)를 만들고, 그리고 그 청사진을 바탕으로한 객체(object)를 만든다는 것을 의미합니다. 하나의 모델이 되는 청사진, 바로 이것이 클래스(class)가 되는 것이고, 그 청사진을 따라 만들어진 것이 객체이면서 그 클래스의 인스턴스(instance)가 됩니다.
이제 구체적인 예시를 들어보겠습니다.
도서관에 있는 책을 표시하고 관리하는 간단한 프로그램을 만든다고 상상해 봅시다. "Book"이라는 클래스를 청사진으로 사용하여 책의 인스턴스를 생성할 수 있습니다. 각 인스턴스는 특정한 책을 나타내며 고유한 속성을 갖습니다.
다음은 자바스크립트 예시입니다.
// Define a class (constructor function) for a Book
function Book(title, author, publicationYear) {
this.title = title;
this.author = author;
this.publicationYear = publicationYear;
// Method to display book information
this.displayInfo = function () {
console.log(`Title: ${this.title}, Author: ${this.author}, Year: ${this.publicationYear}`);
};
}
// Create instances (objects) of the Book class
var book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);
var book2 = new Book("To Kill a Mockingbird", "Harper Lee", 1960);
// Access instance properties and methods
console.log(book1.title); // Output: "The Great Gatsby"
console.log(book2.author); // Output: "Harper Lee"
book1.displayInfo(); // Output: "Title: The Great Gatsby, Author: F. Scott Fitzgerald, Year: 1925"
book2.displayInfo(); // Output: "Title: To Kill a Mockingbird, Author: Harper Lee, Year: 1960"
이 예에서는 다음과 같습니다.
Book : 개체를 생성하기 위한 청사진을 정의하는 클래스(생성자 함수)입니다.
book1, book2 : Book 클래스의 인스턴스입니다. 이러한 인스턴스는 클래스에서 정의한 청사진을 기반으로 생성된 특정 책 개체를 나타냅니다.
이는 JavaScript의 인스턴스가 클래스에서 제공하는 청사진을 따르는 클래스(생성자 함수)에서 생성된 특정 개체인 방법을 보여줍니다.
반응형